← Lessons

quiz vs the machine

Gold1400

Algorithms

The Queue With Circular Buffer

Using head and tail indices that wrap around a fixed array to add and remove without shifting.

5 min read · core · beat Gold to climb

First in first out

A queue serves elements in first in first out order: the earliest added is the first removed. You enqueue at the back and dequeue from the front. A naive array queue shifts every element forward on each dequeue, which is wasteful.

Wrapping around

A circular buffer avoids the shifting. It uses a fixed array with two indices, a head pointing at the front element and a tail pointing at the next free slot. When an index reaches the end of the array, it wraps back to zero, so the used region can straddle the array boundary.

  • Enqueue writes at the tail, then advances the tail with wraparound.
  • Dequeue reads at the head, then advances the head with wraparound.

Both operations touch only one slot, so neither requires shifting.

Full versus empty

The tricky part is telling full from empty, since in both cases the head and tail can meet. Implementations resolve this by tracking a count of stored elements, or by leaving one slot always unused as a marker.

Key idea

A circular buffer queue advances wrapping head and tail indices over a fixed array, giving constant time enqueue and dequeue while a count or spare slot distinguishes full from empty.

Check yourself

Answer to earn rating on the learn ladder.

1. What problem does a circular buffer solve for an array based queue?

2. How do implementations distinguish a full circular buffer from an empty one?

3. Where does enqueue place a new element in a circular buffer?