A queue with a memory budget.
Track head and size separately to distinguish empty from full.
01 Model the idea
A ring buffer reuses a fixed-size array. Logical positions wrap around the physical array with modulo arithmetic. Keep a head index and a size, deriving the next insertion position from them. Unlike an unbounded deque, a bounded queue needs an explicit full policy: reject, block, or overwrite according to the application contract.
0 ≤ size ≤ capacity, and head identifies the oldest queued item.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
INSERT at (head + size) modulo capacity
REMOVE at head and advance head modulo capacity
UPDATE size after either operation03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class RingQueue:
def __init__(self, capacity):
if capacity <= 0: raise ValueError("Positive capacity required")
self.data, self.head, self.size = [None] * capacity, 0, 0
def push(self, value):
if self.size == len(self.data): raise OverflowError("Queue full")
self.data[(self.head + self.size) % len(self.data)] = value
self.size += 1
def pop(self):
if self.size == 0: raise IndexError("Queue empty")
value = self.data[self.head]
self.data[self.head] = None
self.head = (self.head + 1) % len(self.data)
self.size -= 1
return value
queue = RingQueue(2)
queue.push("A"); queue.push("B")
print(queue.pop())
queue.push("C")
print(queue.pop(), queue.pop())A B C
- 1
The head identifies the oldest stored item. Size disambiguates full and empty even when wraparound leads to the same index.
- 2
Clearing the removed slot releases the queue’s reference to the object. That matters if the object is large.
- 3
This queue rejects overflow. collections.deque(maxlen=...) instead discards from the other end when appending at capacity, which is a different contract.
04 Count the cost
O(1) push/pop
O(capacity) storage
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Confirm that a bounded deque keeps the newest two history entries after three appends.
Reveal one possible solution +
from collections import deque
history = deque(maxlen=2)
for value in ["A", "B", "C"]: history.append(value)
print(list(history))06 Check your reasoning
What distinguishes full from empty in this implementation?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.