Patterns: stacks and queues
This chapter 2 review covers three patterns: a monotonic stack for the first larger number to the right, a deque of indexes for the sliding-window maximum, and a queue built from two stacks, in each of which every item goes in and out once, O(n).
Stacks and queues are not hard in themselves; the hard part is seeing which one a problem needs and what goes in it. The three most common kinds of interview problem all have brute-force answers that are O(n²) or O(nk): at n = 100,000 that is billions of comparisons, a certain timeout. With the patterns below, each item goes in and out once, O(n), a few hundred thousand steps. Learn one template for each. The last two stages are calculations exams love: whether a pop order is possible, and how many items a circular queue holds.
Pattern 1: the monotonic stack
The problem: for each number, find the first number to its right that is larger, or −1 if there is none. Two nested loops are O(n²).
The pattern is a monotonic stack: the stack holds the numbers still waiting for an answer (their indexes), and from bottom to top they get smaller and smaller. When a new number x arrives, look at the top: if it is smaller than x, its answer is x, so pop it; keep popping until the top is not smaller than x, then push x.
4index 02index 11index 23index 36index 45index 51def next_greater(a):2 ans = [-1] * len(a)3 stack = [] # indexes still waiting; values decrease bottom to top4 for i, x in enumerate(a):5 while stack and a[stack[-1]] < x:6 ans[stack.pop()] = x # x is the top's answer7 stack.append(i)8 return ans9 10print(next_greater([4, 2, 1, 3, 6, 5]))
[6, 3, 3, 6, -1, -1]
Why it is O(n): each index is pushed once and popped once, so the while turns at most n times in all. Count the difference from two nested loops (the worst case: smaller and smaller at first, so everyone has to look far to the right):
1def brute(a):2 steps = 03 ans = []4 for i in range(len(a)):5 found = -16 for j in range(i + 1, len(a)):7 steps += 18 if a[j] > a[i]:9 found = a[j]10 break11 ans.append(found)12 return ans, steps13 14def mono(a):15 steps = 016 ans = [-1] * len(a)17 stack = []18 for i, x in enumerate(a):19 while stack and a[stack[-1]] < x:20 steps += 121 ans[stack.pop()] = x22 stack.append(i)23 return ans, steps24 25a = list(range(400, 0, -1)) + [1000] # smaller and smaller, then one larger than all26r1, s1 = brute(a)27r2, s2 = mono(a)28print(r1 == r2, s1, s2)
True 80200 400
| Problem | The stack, bottom to top | Pop when |
|---|---|---|
| next greater number | decreasing | a[stack[-1]] < x |
| next smaller number | increasing | a[stack[-1]] > x |
| daily temperatures: days until warmer | decreasing (indexes) | as above, the answer is i - j |
| largest rectangle in a histogram | increasing | a pop works out the rectangle with that bar's height |
Using a monotonic stack on [2, 1, 5, 3, 4], what is "the first bigger number to the right" of each number?
Daily temperatures
✓For each day, how many days until a warmer temperature? 0 if there is none. Use a monotonic stack of indexes: when index j is popped, its answer is i - j.
[1, 1, 4, 2, 1, 1, 0, 0]
1def daily_temperatures(t):2 ans = [0] * len(t)3 stack = [] # indexes still waiting for a warmer day4 for i, x in enumerate(t):5 stack.append(i)6 return ans7 8print(daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]))
Pattern 2: the sliding-window maximum
The problem: a window of length k slides from left to right, and every position needs the window's maximum. Calling max() each time is O(nk).
The pattern is a deque of indexes whose values decrease from front to back:
- If the front index has slid out of the window (
<= i - k),popleft. - Before the new number x joins at the back,
popevery number at the back smaller than x: x is newer and larger, so they can never be the maximum again. - The front is the current window's maximum.
i1from collections import deque2 3def max_window(a, k):4 dq = deque() # indexes; values decrease front to back5 out = []6 for i, x in enumerate(a):7 if dq and dq[0] <= i - k:8 dq.popleft() # the front has slid out of the window9 while dq and a[dq[-1]] < x:10 dq.pop() # smaller than x: can never be the maximum again11 dq.append(i)12 if i >= k - 1:13 out.append(a[dq[0]])14 return out15 16print(max_window([1, 3, -1, -3, 5, 3, 6, 7], 3))
[3, 3, 5, 5, 6, 7]
Compared with scanning every window, here too each index goes in and out of the deque once:
1from collections import deque2 3def brute(a, k):4 steps = 05 out = []6 for s in range(len(a) - k + 1):7 best = a[s]8 for j in range(s, s + k):9 steps += 110 best = max(best, a[j])11 out.append(best)12 return out, steps13 14def with_deque(a, k):15 steps = 016 dq, out = deque(), []17 for i, x in enumerate(a):18 steps += 119 if dq and dq[0] <= i - k:20 dq.popleft()21 while dq and a[dq[-1]] < x:22 steps += 123 dq.pop()24 dq.append(i)25 if i >= k - 1:26 out.append(a[dq[0]])27 return out, steps28 29a = [(i * 37) % 101 for i in range(1000)]30r1, s1 = brute(a, 50)31r2, s2 = with_deque(a, 50)32print(r1 == r2, s1, s2)
True 47550 1979
a = [4, 2, 12, 3, 8, 1] and k = 3. What are the window maximums, in order?
The sliding-window minimum
✓Below is the lesson's code for the window maximum. Change it to the minimum: the values in the deque must increase from front to back.
[2, 2, 3, 1, 1]
1from collections import deque2 3def min_window(a, k):4 dq = deque()5 out = []6 for i, x in enumerate(a):7 if dq and dq[0] <= i - k:8 dq.popleft()9 while dq and a[dq[-1]] < x:10 dq.pop()11 dq.append(i)12 if i >= k - 1:13 out.append(a[dq[0]])14 return out15 16print(min_window([4, 2, 12, 3, 8, 1, 5], 3))
Pattern 3: a queue from two stacks
A favourite interview question: with only stacks (only append and pop), how do you get first in, first out? Use two: in_stack only takes things in, out_stack only gives them out. To dequeue when out_stack is empty, pour everything from in_stack into it: pouring reverses the order, and the earliest one ends up on top.
in_stack
1234out_stack
3211class MyQueue:2 def __init__(self):3 self.in_stack = []4 self.out_stack = []5 self.moves = 0 # how many items were poured in all6 7 def push(self, x):8 self.in_stack.append(x)9 10 def pop(self):11 if not self.out_stack: # pour only when it is empty12 while self.in_stack:13 self.out_stack.append(self.in_stack.pop())14 self.moves += 115 return self.out_stack.pop()16 17q = MyQueue()18for x in [1, 2, 3]:19 q.push(x)20print(q.pop())21q.push(4)22print(q.pop(), q.pop(), q.pop())23 24q = MyQueue()25got = []26for x in range(1000):27 q.push(x)28 if x % 3 == 2:29 got.append(q.pop())30print(got[:5], len(got), q.moves)
1 2 3 4 [0, 1, 2, 3, 4] 333 363
The key is to pour only when out_stack is empty: pour while it still holds items, and the new ones land on top of the old, scrambling the order. Each item is poured only once in its life, so although one dequeue may pour many, on average each is still O(1) (amortized O(1)). Above, 1000 enqueues and 333 dequeues poured only 363 items in all, a little over one per dequeue.
A queue made of two stacks: push 1, 2, pop, push 3, pop again. What does this print?
1class MyQueue:2 def __init__(self):3 self.in_stack = []4 self.out_stack = []5 6 def push(self, x):7 self.in_stack.append(x)8 9 def pop(self):10 if not self.out_stack:11 while self.in_stack:12 self.out_stack.append(self.in_stack.pop())13 return self.out_stack.pop()14 15q = MyQueue()16q.push(1)17q.push(2)18a = q.pop()19q.push(3)20b = q.pop()21print(a, b, q.in_stack, q.out_stack)
[2]. 3 is pushed onto in_stack. At the second pop out_stack is not empty, so 2 comes straight off; 3 stays in in_stack and nothing is poured.In interviews: "The first larger / smaller to the right (or left)" means a monotonic stack; "the maximum / minimum in a window" means a monotonic deque; "a queue from stacks" or "a stack from queues" tests pouring and amortized analysis. Walking a tree or graph level by level (BFS) is a deque too: one level's nodes leave, the next level's join; Chapter 5 writes it.
A queue from two stacks
✓Fill in pop and peek: pour all of in_stack across only when out_stack is empty, then take from the top of out_stack (peek looks without taking).
1 1 2 3 True
1class MyQueue:2 def __init__(self):3 self.in_stack = []4 self.out_stack = []5 6 def push(self, x):7 self.in_stack.append(x)8 9 def pour(self):10 pass # when out_stack is empty, pour all of in_stack across11 12 def pop(self):13 return None14 15 def peek(self):16 return None17 18 def empty(self):19 return not self.in_stack and not self.out_stack20 21q = MyQueue()22q.push(1)23q.push(2)24print(q.peek(), q.pop())25q.push(3)26print(q.pop(), q.pop(), q.empty())
Is a pop order possible
In the stacks lesson we worked it out by hand: pushed 1 2 3, they can't come out as 3 1 2. As a program, it's just doing it: push in order, and after each push, pop for as long as the top is the next one wanted. If the stack ends up empty, the order can be done.
stack
1231def valid(out):2 stack, k = [], 03 for x in range(1, len(out) + 1):4 stack.append(x)5 while stack and stack[-1] == out[k]:6 stack.pop()7 k += 18 return not stack9 10for out in [[3, 2, 1], [3, 1, 2], [2, 4, 3, 1], [4, 1, 2, 3]]:11 print(out, valid(out))
[3, 2, 1] True [3, 1, 2] False [2, 4, 3, 1] True [4, 1, 2, 3] False
Each number goes in once and out at most once: O(n).
Pushed in the order 1 2 3 4 5, which of these cannot be the pop order?
Circular queue questions
Exams define rear in different ways. First check whether rear points at the last element or the next free slot; the formulas change with it:
| rear points at | Length | Full |
|---|---|---|
| the next free slot (the exam style from the queue lesson) | (rear - front + MAX) % MAX | (rear + 1) % MAX == front |
| the last element itself | (rear - front + 1 + MAX) % MAX | (rear + 2) % MAX == front |
In exams: "a circular queue in an array A[0..n]" means n + 1 slots, so MAX = n + 1, not n.
A circular queue with MAX = 10, but this time rear points at the last element itself. front = 7, rear = 2: how many are in it?
How you write it at work
- There is no ready-made function for a monotonic stack: it is a list and a
while. Decide whether the stack holds indexes or values (to work out distances or fill in answers, indexes). - The window maximum uses
collections.deque; for a large window where only the top few matter,heapqworks too, but you must deal with items that have expired. - In Python, a queue from two stacks is never needed: use
deque. The pattern's value is in interviews and "stacks only" settings, and in the idea of amortized O(1) itself (a list'sappend, which grows now and then, is amortized O(1) too).
The task: "for each number, find the first smaller number to its left". Which pattern should you think of?
Summary
Three patterns for stacks and queues
- The monotonic stack: it holds indexes still waiting; a new number first settles the smaller ones, O(n)
- Window maximum or minimum: a deque of indexes; popleft the expired front, pop a back smaller than the new one
- A queue from two stacks: pour only when out is empty; each item is poured once, amortized O(1)
- Each item goes in and out once: that is why all three are O(n)
1stack = []2for i, x in enumerate(a):3 while stack and a[stack[-1]] < x:4 ans[stack.pop()] = x5 stack.append(i)
Chapter 2 quick check
5 questions: in and out of a stack, matching brackets, postfix, circular queue indexes, and the monotonic stack. Work out what each prints before you pick.
Push a, b, c, pop once, then push d. What does it print?
1s = []2for ch in "abc":3 s.append(ch)4s.pop()5s.append("d")6print("".join(s), s[-1])
['a', 'b']; d goes on top of b: abd, and the top s[-1] is d. A stack only changes at its end; a and b never move.Four strings checked in turn. What does it print?
1def ok(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in '([{':6 stack.append(ch)7 elif not stack or stack.pop() != pairs[ch]:8 return False9 return not stack10 11print(ok("([]{})"), ok("(]"), ok("(("), ok(""))
([]{}) every closer pairs with the top and the stack ends empty: True. In (], the ] needs [ but the top is (: False. (( never fails inside the loop, but two are left at the end: return not stack is False. The empty string has no brackets at all and the stack is empty: True.What does the postfix expression 2 3 1 - * come to?
1stack = []2for tok in "2 3 1 - *".split():3 if tok in "+-*":4 b = stack.pop()5 a = stack.pop()6 if tok == "+":7 stack.append(a + b)8 elif tok == "-":9 stack.append(a - b)10 else:11 stack.append(a * b)12 else:13 stack.append(int(tok))14print(stack[0])
- the stack holds 2 3 1: the 1 that comes out first is the right-hand number, so 3 − 1 = 2, leaving 2 2; at *, 2 × 2 = 4. In infix it is 2 * (3 - 1). Swap a and b and it becomes (1 − 3) × 2 = −4.A circular queue with capacity 5, head = 3, size = 4. At which index does the next item go, and at which indexes are the items now?
1cap, head, size = 5, 3, 42print((head + size) % cap, [(head + k) % cap for k in range(size)])
A monotonic stack finds the first larger number to the right of each. What does it print?
1a = [2, 7, 3, 5, 4, 6, 8]2ans = [-1] * len(a)3stack = []4for i, x in enumerate(a):5 while stack and a[stack[-1]] < x:6 ans[stack.pop()] = x7 stack.append(i)8print(ans)