iq.lab
Python starts when a code cell comes near or you run one
05 Stacks and queues

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.

About 1 hour 45 minutes, with the 2 problems worked in it
By the end you can
  • 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.

Step throughA list used as a queue
Step 1 of 15
Line 1 is about to run.
queue = []
queue.append("a.csv")
queue.append("b.csv")
queue.append("c.csv")
while queue:
name = queue.pop(0)
print("load", name)
Names
no names yet
Output
(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.

PredictFront or back

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.

Work it outEmptying a list from the front

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?

moves

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.

OperationWhat it doesCost
deque(items)a new deque holding items, the first one at the front; deque() is emptyO(k) for k items
q.append(x)add x at the backO(1)
q.popleft()remove and return the front itemO(1)
q.appendleft(x)add x at the frontO(1)
q.pop()remove and return the back itemO(1)
q[0], q[-1]read the front, read the backO(1)
len(q), if q:how many items, and whether any are waitingO(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.

Step throughA deque, open at both ends
Step 1 of 10
Line 1 is about to run.
from collections import deque
queue = 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))
Names
no names yet
Output
(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.

Quick checkWhere a deque is slow

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.

Step throughPassing the news down the org chart
Step 1 of 39
Line 1 is about to run.
from collections import deque
reports = {"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)
Names
no names yet
Output
(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.

Put in orderThe last friend in the circle

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • 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.

    Step throughMoving one stack onto another
    Step 1 of 11
    Line 1 is about to run.
    Pushed in the order 1, 2, 3, so the oldest, 1, is at the bottom.
    in_stack = [1, 2, 3]
    out_stack = []
    while in_stack:
    out_stack.append(in_stack.pop())
    print(out_stack[-1])
    Names
    no names yet
    Output
    (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.

    Quick checkMove only when empty

    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.

    Work it outCount the moves

    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?

    moves

    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.

    easyQueues and dequesStackDesign as coding target 15 min

    Queue from two stacks

    Build a queue out of stacks. A queue hands items back in the order they arrived: first in, first out, like a line at a coffee shop. A stack hands back the newest item first: last in, first out, like a pile of plates.

    Write a class MyQueue with four methods. The front of the queue is its oldest item, the next one to leave.

    • push(x) puts x at the back, behind every item already waiting.
    • pop() takes the front item out and returns it.
    • peek() returns the front item and leaves it in place.
    • empty() returns True if no items are waiting and False if any are.

    Store the items only in Python lists used as stacks. On those lists you may call append(x), call pop() with no argument (it removes the last item), read the last item with [-1], and check the length or whether the list is empty. No pop(0), no insert, no other indexes, no deque. The tests cannot see which operations you use, so keeping this rule is up to you, as it would be with an interviewer watching.

    In the examples, the calls run in order on one new MyQueue(). The output lists what the calls return, in order, leaving out push, which returns nothing.

    Example 1
    Inputpush(4), push(7), push(9), peek(), pop(), pop(), empty()Output4, 4, 7, False

    peek() and the first pop() both see 4, the oldest item. The second pop() gets 7. 9 is still inside, so empty() is False.

    Example 2
    Inputpush(3), push(8), pop(), push(5), pop(), pop(), empty()Output3, 8, 5, True

    5 is pushed after the first pop(), but 8 arrived earlier, so 8 leaves first. After the last pop() nothing is left.

    Constraints
    • Pushed values are integers, 0 and negatives included.

    • pop() and peek() are called only when the queue holds at least one item.

    • At most 105 calls in total.

    • Only stack operations on lists: append, pop(), [-1], and checking the length or emptiness.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Code itRolling sums of a stream

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says 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.

    Step throughThe largest in every window of 3
    Step 1 of 43
    Line 1 is about to run.
    from collections import deque
    def 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
    Names
    no names yet
    Output
    (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.

    On paperRun the monotonic deque by hand

    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.

    Total pops (back and front)

    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.

    hardQueues and dequesSliding window target 40 min

    Sliding window maximum

    You get a list of integers nums and a window size k. A window is k neighboring items. Start with the window over the first k items, then slide it right one position at a time until it covers the last k items. Return a list with the largest number in each window, from left to right.

    There are len(nums) - k + 1 windows, so the answer has that many numbers.

    Example 1
    Inputnums = [2, 5, 1, 4, 3, 1, 6], k = 3Output[5, 5, 4, 4, 6]

    The windows are [2, 5, 1], [5, 1, 4], [1, 4, 3], [4, 3, 1] and [3, 1, 6].

    Example 2
    Inputnums = [9, 7, 5, 3], k = 2Output[9, 7, 5]

    The numbers fall, so each window's largest is its first item, and that item leaves on the next slide.

    Example 3
    Inputnums = [-4, 8, -1], k = 1Output[-4, 8, -1]

    A window of one item is its own largest number.

    Constraints
    • 1 ≤ k ≤ len(nums) ≤ 105

    • -105 ≤ nums[i] ≤ 105

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay it like you would in the room

    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).

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint