Building a queue: the ring buffer
🌍 In real life. A small tea stall has a round table with 4 fixed stools, numbered 0 to 3. The owner seats customers going round the table: the next newcomer takes the next stool after the last one taken, and the customer who sat down first is served and leaves first. When stool 3 is taken, the next newcomer sits on stool 0 again, if it is free by then. The stools never move and nobody shuffles along: only the owner's two fingers move, one pointing at who is served next, one at the next free stool.
That is a ring buffer: a queue in a fixed number of slots, used in a circle.
The idea in one sentence: keep a list of exactly capacity slots, a head index for the front and a size; join at (head + size) % capacity and leave from head, moving it on with % capacity, so the indexes wrap round and nothing ever shifts.
Its words:
- ring buffer (or circular buffer): a fixed row of slots used in a circle
- capacity: how many slots there are; size: how many are in use
- head: the slot of the front item; tail: the next free slot,
(head + size) % capacity - wrap round:
% capacityturns the index after the last slot back into 0
How it works, step by step:
- enqueue x: if
size == capacitythe ring is full; otherwise write x at the tail and add 1 to size - dequeue: if
size == 0it is empty; otherwise take the item at head, thenhead = (head + 1) % capacityand take 1 from size
Watch head and tail walk round a ring of 4. The last join wraps round into slot 0:
Why it is correct. The waiting items are always the size slots starting at head and going round: head, head + 1, … each taken % capacity. Joining puts the new item right after the last of them; leaving takes the first of them and moves head on. So the order of arrival is kept, and % lets the same slots be used again and again.
Why keep size? If you only kept head and tail, an empty ring and a full ring would both have head == tail. size tells them apart.
What it costs. Every enqueue and dequeue writes or reads one slot and changes one or two numbers: O(1), always, with no growing and no shifting. Memory is fixed at capacity slots, decided once. That is why ring buffers sit inside keyboards (the keys you type before a program reads them), audio and video players (the next second of sound), and network cards.
In Python you rarely build one: deque(maxlen=k) keeps at most k items, dropping the oldest when a new one arrives.
class RingQueue:
def __init__(self, capacity):
self.slots = [None] * capacity
self.head = 0 # the front item's slot
self.size = 0
def enqueue(self, x):
if self.size == len(self.slots):
raise IndexError("enqueue to a full queue")
tail = (self.head + self.size) % len(self.slots)
self.slots[tail] = x
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError("dequeue from an empty queue")
x = self.slots[self.head]
self.slots[self.head] = None
self.head = (self.head + 1) % len(self.slots) # wrap round
self.size -= 1
return x
q = RingQueue(3)
for x in [10, 20, 30]:
q.enqueue(x)
print(q.dequeue(), q.dequeue())
q.enqueue(40) # goes into slot 0: the ring wraps
print(q.slots, "head", q.head, "size", q.size)from collections import deque
recent = deque(maxlen=3)
for reading in [21, 22, 25, 24, 23]:
recent.append(reading)
print(list(recent))Mistakes and edge cases.
- forgetting
% capacity: the index runs past the last slot and raisesIndexError: list assignment index out of range - telling full from empty by head == tail alone: both look the same; keep size (or always leave one slot empty)
- computing the tail as
head + size - 1: that is the last item, not the next free slot - a full ring must say so (raise, or refuse) unless overwriting the oldest is what you want, as
deque(maxlen=k)does
Quiz
A ring has capacity 5, head 3 and size 4. Which slot does the next item join?
- 2
- 7
- 4
What does this print?
slots = [None] * 3 head = size = 0 for x in [1, 2, 3]: slots[(head + size) % 3] = x size += 1 head, size = (head + 1) % 3, size - 1 # serve 1 slots[(head + size) % 3] = 4 # join 4 size += 1 print(slots, head)This crashes with IndexError once the ring wraps round. Which line is wrong?
class RingQueue: def __init__(self, capacity): self.slots = [None] * capacity self.head = self.size = 0 def enqueue(self, x): tail = self.head + self.size self.slots[tail] = x self.size += 1Why keep size instead of only head and tail?
- An empty ring and a full ring would both have head == tail
- size makes enqueue faster than O(1)
- Python lists need it
What does this print?
from collections import deque d = deque(maxlen=3) for x in [1, 2, 3, 4, 5]: d.append(x) print(list(d))
Coding tasks
Write a class
RingQueue(capacity)that keeps its items in a listself.slotsof exactlycapacityplaces, used in a circle:enqueue(x),dequeue(),is_empty(),is_full()andlen().enqueueon a full queue anddequeueon an empty one raiseIndexError;slotsnever grows.A temperature sensor sends
readingsone after another, but the display only has room for the lastk. Writelast_readings(readings, k): the last k readings (or all of them, if there are fewer), oldest first.