Linear structures and hashing · 10 / 53
Stacks, queues, deques and ring buffers
Understand → trace → implement → justify
2 min reading · allow extra time for practiceStacks are LIFO, queues FIFO, and deques support both ends. Stacks serve undo, bracket matching and explicit DFS. Queues serve BFS and ordered work intake; FIFO dequeue does not imply FIFO completion across concurrent workers.
A ring buffer wraps head/tail modulo capacity. Distinguish full and empty using a size counter, spare slot or generation bit. Specify overwrite, block or reject behaviour. Advancing a head index avoids shifting array contents.
A monotonic deque for sliding-window maxima discards smaller candidates that can no longer win. Each index enters and leaves at most once, so total cost is O(n) despite nested loops. This combines amortised analysis with an invariant. Test empty pops and capacity boundaries.
A worked trace
For [2,1,5,3] with k=3, both windows have maximum 5. On arrival, 5 removes 2 and 1: it is newer and larger.
Cost and assumptions
Deque end operations O(1); sliding-window maxima O(n) time, O(k) space.
Executable example
Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.
from collections import deque
def window_max(a, k):
if not 1 <= k <= len(a):
raise ValueError("invalid window")
q, out = deque(), []
for i, x in enumerate(a):
while q and q[0] <= i-k: q.popleft()
while q and a[q[-1]] <= x: q.pop()
q.append(i)
if i >= k-1: out.append(a[q[0]])
return out
assert window_max([2,1,5,3], 3) == [5,5]TEST YOUR UNDERSTANDING
Your turn
How does a queue differ from a priority queue?
Reveal the reasoning
A queue selects by arrival order; a priority queue selects by a comparator. Similar names, different contracts.
Take it further
- Write down the input contract and the invariant before changing the example.
- Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
- Derive the cost under the stated model; measure several input sizes and explain discrepancies.
Primary reading & lecture notes
Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.
Pat Morin · Open Data Structures ↗