Skip to content

Data Structures

Circular Buffer (Ring Buffer)

write: O(1), always. This holds whether the buffer is empty, partly full, or completely full, because nothing else has to shift.

The idea, in plain English

A circular buffer is like a merry-go-round with a fixed number of seats. New riders keep boarding. Once every seat is taken, the next new rider bumps off whoever has sat there the longest. The 'track' has a fixed size, but it just keeps looping around instead of running out of room.

How it works

  1. 1Reserve a fixed-size array up front — the capacity never grows.
  2. 2Keep track of where the oldest item lives. Call this position start. Also track how many slots are currently filled, called count.
  3. 3write(value): place the new value right after the newest item, wrapping back to index 0 once you run off the end.
  4. 4Once the buffer is full, writing a new value overwrites the oldest one and slides 'start' forward by one.

When you'd use it

Use a circular buffer for streaming the last N sensor readings, a fixed-size 'recent activity' log, audio or video buffering, or any rolling window where old data should fall off automatically.

Common beginner mistakes

  • Don't confuse a circular buffer with a normal array that keeps growing. Its whole point is a fixed size, with old data quietly overwritten.
  • Don't forget the modulo, or wrap-around, math. Without it, the 'next' index walks off the end of the array instead of looping back to 0.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Buffer: 1 2 3
Buffer: 2 3 4
Buffer: 3 4 5
Count: 3

See it in motion

Watch the ring loopCircular buffer · cap 3write: O(1), always. This holds whether the buffer is empty, partly full, or completely full, because nothing else has to shift.

Ready. A fixed ring of 3 slots — writes wrap around with modulo math, nothing ever shifts.

0/3
Fill
– / 0
head / tail
empty
State
0/5
Step
Slot just touchedhead (oldest)tail (next write)Filled

Not sure this is the right topic? See the learning paths → or where this leads →