Sub topic 1
Why a fixed-size queue needs a ring
Prerequisites
This chapter assumes you know:
- Arrays and zero-based indexing.
- The FIFO queue abstraction: enqueue adds an item at the back, dequeue removes the oldest item from the front.
- The modulo operator and bitwise AND.
- Basic Python or C syntax.
The problem
Some programs need a queue whose memory use never changes. Examples are a device driver that receives bytes from hardware, an audio callback that must not call malloc, and a logger that keeps the last 1,000 messages. These programs need three properties:
- A fixed amount of memory, chosen up front.
- O(1) time for both enqueue and dequeue.
- No allocation after startup.
An array looks like a natural fit. The obvious ways to use it as a queue each fail one of these properties.
Attempt 1: shift everything left
Enqueue writes at the end of the array. Dequeue takes items[0] and moves every other item one slot to the left.
class ShiftQueue:
def __init__(self, capacity):
self.items = [None] * capacity
self.size = 0
def enqueue(self, item):
if self.size == len(self.items):
raise OverflowError("queue full")
self.items[self.size] = item
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError("queue empty")
item = self.items[0]
for i in range(1, self.size):
self.items[i - 1] = self.items[i]
self.size -= 1
self.items[self.size] = None
return itemThis works, but dequeue copies up to capacity - 1 items. It costs O(n), and the cost grows as the queue fills.
Attempt 2: move a front index forward
Instead of shifting, keep an index head that marks the oldest item. Dequeue reads items[head] and increments head. This is O(1).
The new problem is that head only moves forward. After capacity dequeues, head points past the end of the array. The slots before head are free, but the write position has also reached the end, so the queue reports "full" even when it holds no items. The memory is not reused.
The only fixes are to shift items back to the start (O(n) again) or to allocate a larger array (which breaks the fixed-memory requirement).
The idea: let the indices wrap
Both indices can wrap around instead of running off the end. When an index reaches the last slot, the next position is slot 0. Freed slots at the front of the array become available again, and no item ever moves.
The array is the same, but you treat it as a circle. This is a circular buffer, also called a ring buffer.
In this picture, slots 2, 3, and 4 hold items. Dequeue reads slot 2 and moves the head to slot 3. Enqueue writes slot 5 and moves the tail to slot 6. When the tail passes slot 7, it continues at slot 0.
What you get
| Approach | Enqueue | Dequeue | Memory reuse | Fixed memory |
|---|---|---|---|---|
| Shift left | O(1) | O(n) | Yes | Yes |
| Forward-only head | O(1) | O(1) | No | Yes |
| Ring buffer | O(1) | O(1) | Yes | Yes |
The cost is that you must now track where the queue starts and where it ends, and you must handle the case where those two positions coincide. The next chapters cover the head and tail indices, the wraparound arithmetic, and that coincidence problem.
Check your understanding
Exercise
A queue is built on a fixed array of 4 slots using a forward-only head index and a write index that never wraps. You enqueue 4 items and dequeue all 4. Why can you not enqueue a fifth item, and what change to the indices fixes this without moving any data?
Show answer
Both indices have reached position 4, the end of the array, so there is no valid slot to write to, even though all 4 slots are free. Letting each index wrap back to 0 after the last slot (for example with (index + 1) % 4) lets the queue reuse the freed slots without moving any item.
Exercise
Why is the shift-left queue unsuitable for a real-time audio callback that dequeues samples on every call?
Show answer
Each dequeue copies up to capacity - 1 items, so its running time grows with the number of stored items. A real-time callback needs a predictable, constant time per call, and a ring buffer provides O(1) dequeue.