Sub topic 4
Circular buffers: a fixed array used as a ring
This chapter assumes you know Python classes, list indexing, the modulo operator, and Big-O notation. It builds on the list-based queue from the earlier chapter, where pop(0) costs O(n) because every remaining element shifts left.
The idea
A circular buffer (also called a ring buffer) is a fixed-size array that you treat as if its end were joined to its start. You never move items. Instead, you track where the queue begins and how many items it holds.
Two values describe the whole queue:
headis the index of the oldest item, the next one to dequeue.sizeis the number of items currently stored.
The tail, where the next item goes, is not stored. You compute it as (head + size) % capacity. The % operator wraps the index back to 0 when it passes the last slot.
Here head = 3, size = 3, and capacity is 5. The tail is (3 + 3) % 5 = 1. Item A is oldest, then B, then C, which wrapped around to slot 0.
Implementation
class RingQueue:
def __init__(self, capacity):
self._buf = [None] * capacity
self._head = 0
self._size = 0
def __len__(self):
return self._size
def enqueue(self, item):
if self._size == len(self._buf):
raise OverflowError("queue is full")
tail = (self._head + self._size) % len(self._buf)
self._buf[tail] = item
self._size += 1
def dequeue(self):
if self._size == 0:
raise IndexError("dequeue from empty queue")
item = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % len(self._buf)
self._size -= 1
return itemWalk through the two operations:
enqueuechecks for a full buffer, computes the tail slot, writes the item, and increasessize.dequeuechecks for an empty buffer, reads the item athead, advancesheadby one with wraparound, and decreasessize.
Both do a fixed number of steps, so both are O(1). Nothing shifts.
Setting the vacated slot to None in dequeue is a small but useful detail. Without it, the array would keep a reference to the removed object and delay garbage collection.
Tracing a wraparound
Use a capacity of 3 and follow head and size:
| Step | Operation | `head` | `size` | Array contents |
|---|---|---|---|---|
| 0 | start | 0 | 0 | `[None, None, None]` |
| 1 | enqueue "a" | 0 | 1 | `["a", None, None]` |
| 2 | enqueue "b" | 0 | 2 | `["a", "b", None]` |
| 3 | dequeue (returns "a") | 1 | 1 | `[None, "b", None]` |
| 4 | enqueue "c" | 1 | 2 | `[None, "b", "c"]` |
| 5 | enqueue "d" | 1 | 3 | `["d", "b", "c"]` |
At step 5 the tail is (1 + 2) % 3 = 0, so "d" lands in slot 0. The buffer is now full, and a further enqueue raises OverflowError.
Why track size instead of a tail index
Many textbooks store head and tail indices only. That design has an ambiguity: when head == tail, the queue could be empty or completely full. Fixes include wasting one slot, or keeping a flag.
Storing size removes the ambiguity. Empty means size == 0, and full means size == capacity. All capacity slots are usable.
Common errors
- Forgetting the modulo on
head. Ifheadgrows without wrapping, the nextdequeuereads past the end of the array and raisesIndexError, or silently reads the wrong slot after a later change. - Capacity of zero.
% 0raisesZeroDivisionError. Validate that capacity is at least 1 in__init__if the class is public. - Treating a full buffer as growable. This class has a fixed size by design. Growing means allocating a new array and copying items out in queue order, starting from
head, which costs O(n) for that one operation. - Reading the array directly.
_bufis in storage order, not queue order. After wraparound, index 0 may hold the newest item.
Trade-offs
A circular buffer gives O(1) operations and no per-item allocation, and its memory is contiguous, which is cache friendly. The cost is a fixed capacity that you must choose in advance. It suits cases where a bound is natural, such as buffering audio samples or limiting a backlog.
When you need an unbounded queue in Python, collections.deque is usually the better choice. Later chapters cover it, including maxlen, which gives ring-buffer behavior with overwriting.
Exercise
A RingQueue has capacity 4, head = 3, and size = 3. At which array index will the next enqueue store its item, and what will head be after the next dequeue?
Show answer
The tail is (3 + 3) % 4 = 2, so the next item is stored at index 2. A dequeue reads the item at index 3 and sets head to (3 + 1) % 4 = 0.
Exercise
Add a peek method to RingQueue that returns the oldest item without removing it. What should it do on an empty queue, and what is its cost?
Show answer
def peek(self): if self.size == 0: raise IndexError("peek from empty queue") return self.buf[self._head] It raises IndexError on an empty queue, matching dequeue, and costs O(1) because it reads one slot.