Lesson 3 of 3
Queues and deques
A queue hands back the oldest item first. Python's deque adds and removes at both ends in O(1), so it is the notebook for work in arrival order, and, kept in falling order, it finds the largest number in every window in one pass.
Use a list, then a deque, as a first-in, first-out queue and trace what leaves when
Say why list.pop(0) costs O(n) and what deque.popleft() does instead
Use a queue as the notebook for handling items in the order they arrived
Build a queue from two stacks and explain why it is O(1) amortized
Find the largest number in every window of k items with a monotonic deque in O(n)
Files land in an upload folder all morning: a.csv at 9:00, b.csv at 9:01, c.csv at 9:02. Your loader must take them in the order they arrived, because each file corrects rows in the one before it. The stack from the first lesson of this module would hand you c.csv first, the newest. Here you need the oldest first.
That order has a name, first in, first out (FIFO), and the structure that keeps it is a queue. This lesson makes a queue fast in Python, uses one as the notebook for work that must happen in arrival order, builds one out of two stacks (a classic problem, rated easy), and ends with a hard problem that needs both ends at once: the largest number in every window.
First in, first out
Which item leaves a queue next? Picture a line at a coffee shop. New items join at the back, and the item that leaves is always the one at the front, the one that has waited longest. Two words to keep straight: the front is where items leave, and the back is where they join. Joining is also called enqueue, and leaving dequeue. A stack is the opposite: it hands back the newest item.
A Python list can act as a queue. append(x) adds x at the back. pop(0) removes the item at index 0, the front, and returns it. The loop while queue: repeats as long as the list holds at least one item, the same test as if stack: in the first lesson. Before you step through, guess the order of the three load lines.
queue = []queue.append("a.csv")queue.append("b.csv")queue.append("c.csv")while queue:name = queue.pop(0)print("load", name)
(nothing printed yet)pop(0) and pop() differ by one argument and mean opposite things. pop() with no argument removes the last item, the newest: stack order. pop(0) removes the first item, the oldest: queue order. This one mixes both. Predict it.
This list is used as a queue, and once as a stack. Type exactly what it prints: one line for each print, four lines in all.
line = []
line.append("ann")
line.append("bo")
print(line.pop(0))
line.append("cy")
line.append("dee")
print(line.pop(0))
print(line.pop())
print(line)
A deque: fast at both ends
Why not always use a list as a queue? It gives the right order. The problem is cost. Recall how a list is stored (module 3): its items sit in consecutive memory slots, and the address of nums[i] is start + i × 8, where start is the address of the first slot. The formula counts from the first slot, so item 0 must always sit there. So when pop(0) removes the first item, every other item shifts one slot left to close the gap.
The figure is a list of five numbers in memory, one box per slot, with dashed boxes for spare room. A move is one item copied into a neighboring slot, and the readouts count them: moves for this operation, and total moves so far. Press Pop front a few times and count the moves. Then compare Pop, which removes the last item.
Emptying a list of n items with pop(0) costs (n − 1) + (n − 2) + ... + 1 + 0 moves, about n2/2. That is O(n2) for a job that should be O(n). With 100,000 queued items it is about 5 billion moves.
A list holds 6 items. You empty it by calling pop(0) six times. Count one move for every item shifted one slot left, as the figure does. How many moves in total?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
collections.deque adds and removes at both ends in O(1). The name is short for double-ended queue and is said "deck" (not "dequeue", the word for leaving a queue). It does not keep its items in one row of slots. It keeps them in a chain of small blocks and remembers where the front and the back are, so removing the front moves a marker instead of shifting items.
| Operation | What it does | Cost |
|---|---|---|
deque(items) | a new deque holding items, the first one at the front; deque() is empty | O(k) for k items |
q.append(x) | add x at the back | O(1) |
q.popleft() | remove and return the front item | O(1) |
q.appendleft(x) | add x at the front | O(1) |
q.pop() | remove and return the back item | O(1) |
q[0], q[-1] | read the front, read the back | O(1) |
len(q), if q: | how many items, and whether any are waiting | O(1) |
The trace runs the four operations that change a deque, then reads both ends and the length. The state panel draws a deque as a row with "front" and "back" labels. Before you step through, guess the five numbers the last line prints.
from collections import dequequeue = deque()queue.append(4)queue.append(7)queue.append(9)front = queue.popleft()queue.appendleft(1)back = queue.pop()print(front, back, queue[0], queue[-1], len(queue))
(nothing printed yet)A deque is fast at its ends, not in the middle. Reading q[i] far from both ends walks the chain of blocks, so it is O(n). A list makes the other trade: any index in O(1), but the front costs O(n). Use a deque whenever items leave from the front. append to join and popleft to leave stay O(1) however long the line gets.
An empty deque has no front. Like pop() on an empty list, popleft() on an empty deque raises an IndexError, and so does q[0]. Guard them with while q: or if q: whenever the deque could be empty.
q is a deque holding 100,000 numbers. Which of these is not O(1)?
Choose one answer, then check.
A queue as the notebook
Many problems say: handle things in the order they arrived, where handling one thing can add more things to handle. A queue is the notebook for that. Here is a small org chart. Ana manages Ben and Cy, Ben manages Dee, and Cy manages Eve and Fay. Ana tells her direct reports some news, and everyone who hears it tells theirs. The queue holds the people who have heard the news and not yet passed it on.
The dict reports lists each manager's direct reports. People who manage nobody are left out, so the code reads it with reports.get(person, []), which gives an empty list for a missing key. deque(["ana"]) starts the line with Ana already in it. Before you step through, guess the order of the six names it prints.
from collections import dequereports = {"ana": ["ben", "cy"], "ben": ["dee"], "cy": ["eve", "fay"]}queue = deque(["ana"])while queue:person = queue.popleft()print(person)for report in reports.get(person, []):queue.append(report)
(nothing printed yet)The queue hands out people level by level. Call a person's level the number of managers above them: Ana is level 0, Ben and Cy level 1, and Dee, Eve and Fay level 2. The output is level 0, then level 1, then level 2. Nothing in the code mentions levels. Arrival order produced them, because everyone at one level joined the line before anyone at the next.
This walk is breadth-first search, or BFS: everything one step away before anything two steps away. Module 8 uses it to read a tree level by level, and module 10 to find shortest paths. Swap popleft() for pop() and the same loop goes deep first, the stack's walk: ana, cy, fay, eve, ben, dee.
Everyone here has exactly one manager, so nobody hears the news twice and the queue alone is enough. In a network where two routes can reach the same place, such as flights between cities, a place could join the line twice. There BFS also keeps a set of the places that have already joined. Module 10 adds that set.
A queue also runs turns: the item at the front takes a turn, then leaves or goes to the back. Put this game together from its lines.
Friends numbered 1 to n stand in a circle, which we keep as a queue. Each round, the first k - 1 friends at the front move to the back, one at a time. Then the friend now at the front leaves. When one friend is left, return that friend's number.
Put the lines in order to build last_friend(n, k). deque is already imported. Two lines do not belong.
Add lines from the list below, in order.
circle.appendleft(circle.pop())def last_friend(n, k):return circle[0]circle.popleft()while len(circle) > 1:circle = deque(range(1, n + 1))circle.append(circle.popleft())for _ in range(k - 1):circle.pop()
A queue from two stacks
Can you get queue order when all you have is stacks? A classic problem asks exactly that. It practices two skills: getting one order out of the other, and explaining a cost that is cheap on average but not on every call.
The key move: popping every item off one stack onto another reverses their order. The oldest item, buried at the bottom, comes out on top. The trace draws both lists as stacks, top item at the top. Before you step through, guess what the last line prints.
in_stack = [1, 2, 3]out_stack = []while in_stack:out_stack.append(in_stack.pop())print(out_stack[-1])
(nothing printed yet)So keep two stacks with two jobs. in_stack takes every new item. out_stack hands items out, oldest on top. When the front is needed and out_stack is empty, move everything over. When out_stack still holds items, leave in_stack alone: everything waiting in out_stack is older than anything in in_stack. Test that rule before you write the class.
This two-stack queue moves items from in_stack to out_stack on every pop, not only when out_stack is empty:
in_stack = []
out_stack = []
def push(x):
in_stack.append(x)
def pop():
while in_stack:
out_stack.append(in_stack.pop())
return out_stack.pop()
push(1)
push(2)
print(pop())
push(3)
print(pop())
What does the second print show?
Choose one answer, then check.
What does one pop cost? A pop that finds out_stack empty moves every item in in_stack, so a single call can cost O(n). But each item moves from in_stack to out_stack at most once in its life. So n calls do at most n moves in total, even when one call does many, and averaged over the whole run, pop and peek (read the front without removing it) cost O(1) per call. That average over a run of calls is the amortized cost from module 2, where a rare slow append was paid for by many fast ones. The monotonic stack in the previous lesson used the same count. Check it on a short run of calls.
A correct two-stack queue (it moves items only when out_stack is empty) runs these calls: push 1, push 2, push 3, push 4, pop, push 5, pop, pop, pop, pop. How many items move from in_stack to out_stack in total?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now build it. The problem wraps the two stacks in a class, as min stack did in the first lesson: __init__ runs once when a MyQueue is made and creates the two lists, and each method reaches them through self. Only stack operations are allowed on the lists, so no pop(0) and no deque.
The largest in every window
The last idea needs both ends of a deque at once. A sensor sends one reading per minute, and a dashboard shows the peak of the last 3 minutes. Given all the readings, list the largest number in every window of k neighboring readings.
A window sum slides in O(1) per step (module 4): add the item that enters on the right, subtract the item that leaves on the left. When readings arrive one at a time and are not kept, a deque holds the window: the newest reading joins at the back, and the one that leaves is at the front. Write that version first.
Readings arrive one at a time. After each one, report the sum of the last k readings (of all readings so far, while fewer than k have arrived). Write rolling_sums(readings, k), which returns those sums as a list.
Treat readings as a stream: keep the window in a deque and a running total, and do not re-add the window on every step. Then press Watch it run to see the window slide.
raise NotImplementedError, then press Run tests. Each check says what it expects.This module's problem list has a practice problem built the same way: recent calls (LeetCode 933) keeps a deque of request times and drops the times older than 3,000 milliseconds from the front.
A maximum cannot subtract. Take [4, 2, 3, 1, 5] with k = 3. The windows are [4, 2, 3], [2, 3, 1] and [3, 1, 5]. When the window slides from the first to the second, the 4 leaves, and it was the largest. One running maximum cannot tell you the new largest, 3. The brute force recomputes max for every window: n − k + 1 windows of k items, O(nk).
The fix starts with the items that can never win. In [4, 2, 3], once the 3 arrives, the 2 is useless: every window from now on that holds the 2 also holds the 3, which arrived later, leaves later, and is bigger. An older item is out for good once a newer item at least as big arrives. Throw those items out, and the ones left, called candidates, have values that fall from oldest to newest.
The window's largest value is always a candidate. Take its newest copy in the window: nothing after it is at least as big, so nothing knocked it out. And since the candidates' values fall, the largest is the oldest candidate still in the window.
The candidates need two exits. Knocked-out items leave from the back, where new items arrive, as the monotonic stack in the previous lesson popped smaller items. One difference: here an equal item is knocked out too, because the newer copy is as big and stays in the window longer. The oldest candidate leaves from the front once the window slides past it. Two exits make it a deque, a monotonic deque: monotonic (moving in one direction only) because its values only fall from front to back.
The deque stores indexes, not values, because an index says when the front has slid out. The window ending at index i starts at i - k + 1, so an index of i - k or less is outside. With k = 3, the window ending at index 3 covers indexes 1, 2 and 3, and index 0 is out: 0 ≤ 3 − 3. The first window is full at i = k - 1, so answers start there.
Before you step through, guess which indexes candidates holds when the walk ends.
from collections import dequedef max_sliding_window(nums, k):candidates = deque()out = []for i, x in enumerate(nums):while candidates and nums[candidates[-1]] <= x:candidates.pop()candidates.append(i)if candidates[0] <= i - k:candidates.popleft()if i >= k - 1:out.append(nums[candidates[0]])return out
(nothing printed yet)Two details in the code. Line 10 is an if, not a while: the window moves one index per pass, so at most one index can slide out. And line 10 can read candidates[0] without checking for an empty deque, because line 9 has just appended i.
The inner while can pop several indexes for one new number, and the walk is still O(n). Count pops instead of loop passes: each index is appended once and popped at most once, from one end or the other, so the whole walk does at most n pops. This is the same counting argument that made the two-stack queue O(1) amortized and the monotonic stack O(n). Run it by hand on a new list and count the pops.
Run max_sliding_window([6, 1, 3, 2, 0, 4], 3) from the trace above by hand. Make one row per index i: x, the indexes popped from the back, whether the front slid out, candidates at the end of the step (with their values), and what is recorded. Then count every pop, from the back and from the front.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write it yourself. The workspace has hints, the brute force, and a large test where O(nk) runs out of time.
This module's problem list has a medium built from the same deque: longest run within a limit (LeetCode 1438) keeps two monotonic deques, one for the largest and one for the smallest, inside a window that grows and shrinks.
Last, practice the plan out loud. These are the sentences you will say before you type.
An interviewer asks for the largest number in every window of k neighboring items. Before typing, say your plan: the brute force and its cost, then the walk, the notebook, the promise, and why the better version is O(n).
Saved in this browser as you type.