← chapter

Circular and ring buffers

A fixed-size FIFO laid out in a circle. The write position wraps around.

The whole trick: modulo

Watch it wrap and overwrite

Slots stay put; positions travel. Tail wraps past the end; oldest gets overwritten when full.

Scratch vs library

Both O(1). deque(maxlen) ≈10× faster (C vs a Python modulo per push).

Where you meet it

Takeaway

Fixed array + two wrapping indices = an endless queue in O(capacity) memory. Worst-case O(1), no GC pauses. Next tier: hashing.