Queues & Deques
What is a queue?
Add at the back, remove from the front: FIFO (first in, first out).
Use collections.deque, not a list
list.pop(0) is O(n) because every item shifts. A deque (double-ended queue) does both ends in O(1):
| Operation | deque | Big O |
|---|---|---|
| add to the back | q.append(x) | O(1) |
| remove from the front | q.popleft() | O(1) |
| add to the front | q.appendleft(x) | O(1) |
| remove from the back | q.pop() | O(1) |
| peek at the front | q[0] | O(1) |
Where queues appear
- Task scheduling: print jobs, background jobs, message queues
- Breadth-first search: exploring level by level (Unit 10)
- Buffers: keyboard input, video streaming
- Rate limiting: keep timestamps of the last N requests
Variations
- Deque: works as a stack and a queue.
- Circular queue: a fixed-size array whose end wraps around to the start.
- Priority queue: removes the most important item first, not the oldest (Unit 9, heaps).
Pattern: sliding window maximum
A deque of indexes, kept in decreasing value order, gives the max of every window of size k in O(n).
Example
from collections import deque
# Simple task queue
tasks = deque(["email", "report", "backup"])
tasks.append("deploy")
while tasks:
print("Doing:", tasks.popleft())
# email, report, backup, deploy
# Recent-items buffer: keeps only the last 3
recent = deque(maxlen=3)
for page in ["home", "about", "blog", "contact"]:
recent.append(page)
print(list(recent)) # ['about', 'blog', 'contact']
# Sliding-window maximum in O(n)
def window_max(nums, k):
dq, out = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
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]