← all tracks/Puzzle Workshop: Explorer

Queues & Deques: Wait Your Turn

Queues & Deques: Wait Your Turn 🚶🚶🚶

The stack's polite sibling: the queue. First in, first out — like every fair line you've ever stood in.

With a plain list, you feed the back and serve the front:

line = []
line.append("mia")     # join the back
first = line.pop(0)     # serve the front

Queues run lunch lines, print jobs, and every "wait your turn" system in the world. And when a line bites its own tail, it becomes a circle — pass the front person to the back and you can rotate forever. Hot potato, chore wheels, dealing cards: all rotating queues (with the % remainder as the teleport-shortcut for when you don't need the drama).

Earning the deque

Here's the dirty secret of pop(0): every single person behind the front has to shuffle forward one spot. For a short line, fine. For a million-person line — ouch. Python's toolbox has a line built for BOTH ends, with no shuffling:

from collections import deque
line = deque()
line.append("leo")       # join the back
line.appendleft("vip")   # jump the front
line.pop()                # leave from the back
line.popleft()            # serve the front

The final cluster puts the deque to work on double-door buses, arcade snakes — and a trick called the sliding window that keeps "the last k things" fresh forever. It's the last data structure of your journey, and it was worth the wait. NEXT, PLEASE!

# problems