Queues and Deques (DSA #5)
A customer support line does not serve the last caller first; it serves whoever has waited longest. First-in-first-out is what makes the system feel fair, and it is exactly what a queue guarantees. The stack gave us “most recent”; the queue gives us “earliest”, and that ordering change is what turns a depth-first walk into a breadth-first one.
This chapter covers the queue interface, the circular-buffer implementation that makes it efficient, the deque, and the patterns queues unlock: BFS, task scheduling, and the monotonic deque for sliding-window maximum.
FIFO: the interface
- enqueue(x) — add at the back.
- dequeue() — remove and return from the front.
- peek() — look at the front.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.9cm, minimum height=0.62cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {4,2,9,1} {
\node[c, fill=blue!12] at (\i*0.95,0) {\v};
}
\draw[->, thick, green!45!black] (-0.9,0) -- (-0.42,0) node[midway, above, font=\scriptsize] {dequeue};
\draw[->, thick, orange!75!black] (3.75,0) -- (4.25,0) node[midway, above, font=\scriptsize] {enqueue};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.4,-0.6) {leaves at the front, arrives at the back};
\end{tikzpicture}
The wrong way and the right way
A naive array queue is a trap. If the front is always index 0, dequeuing means shifting everything left — \(O(n)\).
# BAD: dequeue is O(n) because every remaining element shifts
class BadQueue:
def __init__(self): self.data = []
def enqueue(self, x): self.data.append(x) # O(1)
def dequeue(self): return self.data.pop(0) # O(n)!
The fix is to let the front drift and reuse the freed slots in a circle — a circular buffer.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.62cm, minimum height=0.62cm, font=\scriptsize, circle}]
\foreach \i in {0,...,7} {
\pgfmathsetmacro{\ang}{90 - \i*45}
\draw[thick] (\ang:1.5) circle (0.31);
}
\node[c, fill=green!28] at (90:1.5) {4};
\node[c, fill=blue!14] at (45:1.5) {2};
\node[c, fill=blue!14] at (0:1.5) {9};
\node[c, fill=blue!14] at (-45:1.5) {1};
\node[c, fill=gray!12] at (-90:1.5) {};
\node[font=\scriptsize\ttfamily, text=green!45!black] at (90:2.15) {front};
\node[font=\scriptsize\ttfamily, text=orange!75!black] at (-90:2.15) {back};
\node[font=\rmfamily\small, text=black!60] at (0,-2.15) {enqueue/dequeue wrap around the buffer};
\end{tikzpicture}
A circular buffer stores head, tail, and count in a fixed array; enqueue and dequeue move the indices and wrap with modulo, both \(O(1)\).
class CircularQueue:
def __init__(self, cap):
self.data = [None] * cap
self.head = self.count = 0
def enqueue(self, x):
if self.count == len(self.data):
raise OverflowError
self.data[(self.head + self.count) % len(self.data)] = x
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError
x = self.data[self.head]
self.head = (self.head + 1) % len(self.data)
self.count -= 1
return x
In Python you rarely hand-roll this; collections.deque is a doubly linked list of blocks that gives \(O(1)\) at both ends.
from collections import deque
q = deque([4, 2, 9])
q.append(1) # enqueue at the back
q.popleft() # dequeue from the front -> 4
q.appendleft(0) # push to the front
q.pop() # pop from the back
Deque: the double-ended queue
A deque allows insertion and removal at both ends, all \(O(1)\). It is the data structure behind:
- Sliding-window maximum (below).
- 0-1 BFS, where edges of weight 0 push to the front and weight 1 to the back.
- Palindrome checking, comparing both ends.
Application: BFS
A queue is what makes breadth-first search breadth-first: you visit all neighbors at distance \(d\) before any at distance \(d+1\).
from collections import deque
def bfs(graph, start):
seen = {start}
q = deque([start])
order = []
while q:
node = q.popleft() # earliest discovered first
order.append(node)
for nb in graph[node]:
if nb not in seen:
seen.add(nb)
q.append(nb)
return order
Swap the queue for a stack and the same code becomes DFS (Chapter 20). The only difference is which end you take from — a one-line change with very different traversal orders.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.66cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!30] (r) at (0,0) {0};
\node[n, fill=blue!12] (a) at (-1.6,-1) {1}; \node[n, fill=blue!12] (b) at (1.6,-1) {2};
\node[n] (c) at (-2.3,-2) {3}; \node[n] (d) at (-0.9,-2) {4};
\node[n] (e) at (0.9,-2) {5}; \node[n] (f) at (2.3,-2) {6};
\draw[a] (r) -- (a); \draw[a] (r) -- (b);
\draw[a] (a) -- (c); \draw[a] (a) -- (d);
\draw[a] (b) -- (e); \draw[a] (b) -- (f);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.6) {all of distance 1, then all of distance 2};
\end{tikzpicture}
Application: sliding-window maximum with a monotonic deque
Given an array and a window size \(k\), return the maximum of every window. Recomputing each window is \(O(nk)\). A deque of indices with decreasing values does it in \(O(n)\): the front is always the current window’s maximum, and we pop from the back anything smaller than the newcomer.
from collections import deque
def window_max(nums, k):
dq, out = deque(), [] # indices, values decreasing
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x: # smaller values can never win
dq.pop()
dq.append(i)
if dq[0] <= i - k: # front fell out of the window
dq.popleft()
if i >= k - 1:
out.append(nums[dq[0]])
return out
print(window_max([1, 3, -1, -3, 5, 3, 6, 7], 3)) # [3, 3, 5, 5, 6, 7]
This is the same amortized reasoning as the monotonic stack: each index enters and leaves the deque once, so the total is \(O(n)\).
Other uses
- Task/work queues. Producer–consumer buffers (Chapter 13 of the system design course), rate limiters, and print queues all rely on FIFO fairness.
- Scheduling. Round-robin scheduling rotates through a ready queue.
- Level-order tree traversal. Print a tree level by level using a queue (Chapter 9).
Pitfalls
list.pop(0). It is \(O(n)\) because it shifts the tail; usedeque.popleft()for \(O(1)\).- Forgetting the empty check. Dequeuing an empty queue must raise or return a sentinel, not crash the program.
- Using a queue for DFS. The traversal order flips; make sure FIFO is what you intend.
- Not bounding the queue. An unbounded producer–consumer queue grows forever under imbalance; cap it and apply back pressure.
- Confusing
deque.pop()andpopleft(). They remove from opposite ends; mixing them silently reverses your logic.
Why is list.pop(0) \(O(n)\) but deque.popleft() \(O(1)\)? What ordering does a queue guarantee, and which traversal needs it?
ASolution
pop(0) shifts every remaining element left to keep the front at index 0, while a deque’s blocks allow removal from the front in constant time. A queue guarantees first-in-first-out, which BFS needs to visit all nodes at one distance before the next.
Next: Hash Tables (DSA #6) — turning a search into a lookup.