Circular Buffer

A fixed-size array that wraps around: once the end is reached, writes continue from the beginning, overwriting the oldest data. O(1) push/pop at both ends with zero reallocation.

A circular (ring) buffer is a fixed-size array with two indices, head and tail, that wrap around via modulo arithmetic. Writing advances tail (mod capacity); reading advances head (mod capacity) — there is no shifting of existing elements, unlike a plain array-based queue.

When the buffer is full, a new write either fails or overwrites the oldest unread element (head), depending on the variant — the "overwrite" mode is exactly what makes ring buffers ideal for "keep only the most recent N items" use cases like audio buffers and log tails.

Because capacity is fixed at construction, there is no dynamic resizing to amortise — every operation is a strict O(1), which is precisely why ring buffers are the default choice in real-time and embedded systems where allocation pauses are unacceptable.

Operations

OperationComplexity
push (write)O(1)
pop (read)O(1)
peekO(1)
resizenot supported — fixed capacity

Where it's used

Audio/video streaming buffers, producer-consumer pipelines, keeping a bounded recent-history log, embedded/real-time systems avoiding dynamic allocation.

Open the interactive Circular Buffer workspace →