Lesson 2 of 3
Monotonic stacks
For each item, find the next bigger item to its right. Scanning right from every item is O(n²). One walk with a stack of items still waiting for an answer does it in O(n), and the same stack finds the largest rectangle under a bar chart.
Find the next greater element for every item with the scan-right brute force, and say why it costs O(n2)
Trace a monotonic stack and say which items are waiting after each step
Explain why a while loop inside the for loop still costs O(n) in total
Choose what goes on the stack (values or indexes) and whether the pop test is strict
Find the largest rectangle in a histogram from each bar's first shorter bar on both sides
A dashboard shows one number per day: [3, 1, 2, 5, 4]. The analyst wants one more column: for each day, the number from the next day that did better. Day 0 had 3, and the first bigger number after it is the 5 on day 3. Day 1 had 1, and the 2 right after it already beats it. Day 3 had 5, and nothing after it is bigger, so its answer is -1.
This question, "what is the next bigger item to my right?", is called the next greater element. It hides inside warmer days, stock spans and the largest rectangle under a bar chart. The slow answer is a loop inside a loop. The fast answer is one walk with a stack, where every item waits until something bigger arrives.
The slow way: scan right from every item
Here is the question exactly. For each position i, the answer is the first item to the right of i that is strictly bigger than nums[i], or -1 if there is none. The first bigger item, not the biggest: for the 1 on day 1 the answer is the 2, even though a 5 comes later.
The plan you would say first in an interview is the brute force, the direct method that checks everything: for each item, scan to its right until something bigger shows up. The outer loop picks the item. The inner loop scans, and break stops it as soon as the answer is found. In the trace, the arrow i marks the item that wants an answer and j marks the cell being checked. Before you step through, guess how many times line 5, the comparison, runs in all.
def next_greater_slow(nums):answer = [-1] * len(nums)for i in range(len(nums)):for j in range(i + 1, len(nums)):if nums[j] > nums[i]:answer[i] = nums[j]breakreturn answer
(nothing printed yet)Look at the work the scans repeat. The scan for the 3 walked past the 1 and the 2. Then the 1 and the 2 each started a scan of their own over the same cells. The worst case is a list that only falls, like [5, 4, 3, 2, 1]. Count its comparisons before you read on.
The scan-right version runs the comparison nums[j] > nums[i] once for every cell j it checks. How many comparisons does it make on [5, 4, 3, 2, 1]? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
In a falling list no item has a bigger item to its right, so break never runs and every scan goes to the end. With n items that is (n − 1) + (n − 2) + ... + 1 + 0 = n(n − 1)/2 comparisons, which is O(n2). For 10,000 items, about 50 million.
Turn it around: who is still waiting?
The slow version makes each item search for its answer. Turn the question around. When the walk reaches a new item x, ask: whose answer is x? It is the answer for every earlier item that is smaller than x and has no answer yet. Call the items with no answer yet waiting.
Now the key fact. From oldest to newest, the waiting items never get bigger. If a newer waiting item were bigger than an older one, it would have answered the older one when it arrived, and the older one would not be waiting. So when x arrives, look at the newest waiting item first. If it is smaller than x, x is its answer: remove it and look at the next newest. Stop at the first waiting item that is not smaller, because every older one is at least as big.
Newest first, removed from the newest end: that is the stack from the previous lesson, a list we only touch at its end, called the top. append pushes an item on top, pop() removes the top item and returns it, and stack[-1] reads the top without removing it. A stack whose values never rise from bottom to top (or, in other problems, never fall) is called a monotonic stack, from "monotonic", moving in one direction only.
We push indexes, not values. An index j tells us where to write the answer, answer[j], and nums[j] still gives the value. So the top item is nums[stack[-1]]: stack[-1] is an index, and nums at that index is the item. The trace's while line, line 5, reads "while the stack has an item and the top item is smaller than x". and stops at the first false side, so on an empty stack the code never reads stack[-1].
The trace draws stack standing up with its top at the top, and the arrows i and j under nums. Before you step through, guess: which items are still waiting on the stack when the walk ends, and what answer do they get?
def next_greater(nums):answer = [-1] * len(nums)stack = []for i, x in enumerate(nums):while stack and nums[stack[-1]] < x:j = stack.pop()answer[j] = xstack.append(i)return answer
(nothing printed yet)Why the answer is right. When x pops index j, item j was still waiting, so no item between them was bigger than nums[j] (that item would have popped j first). And x is bigger. So x is the first bigger item to the right of j, which is exactly its answer. An index still on the stack at the end was never popped, so no item after it was bigger, and -1 is right.
Try it on a new list before you watch it run.
This is the stack version from the trace, with one extra line: it prints the stack (a list of indexes) when the walk ends. Type exactly what the program prints: two lines.
def next_greater(nums):
answer = [-1] * len(nums)
stack = []
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
j = stack.pop()
answer[j] = x
stack.append(i)
print(stack)
return answer
print(next_greater([4, 2, 1, 3, 6, 5]))
The heart of the pattern is the loop that keeps the stack in order. The next puzzle keeps only that loop. The items left on the stack at the end are exactly the items with nothing bigger to their right, so the stack itself is the answer.
Put the lines in order to build no_bigger_to_the_right(nums). It returns the values that have no bigger value anywhere to their right, in their original order. There is no answer list this time: a value that gets popped has met something bigger, so whatever is left on the stack at the end is the answer. The stack holds values here, not indexes. Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
for x in nums:if stack and stack[-1] < x:stack = []stack.pop()while stack and stack[-1] < x:stack.append(x)while stack and stack[-1] > x:return stackdef no_bigger_to_the_right(nums):
To recap: the stack holds the indexes still waiting for an answer, and their values never rise from bottom to top. A new item pops every smaller waiting item and answers it, then waits itself.
Why one walk is O(n)
A while loop inside a for loop usually means O(n2). Here it does not, and the reason is worth saying out loud in an interview. Count stack moves instead of loop passes. On [3, 1, 2, 5, 4]:
| index | item | pushed when | popped when |
|---|---|---|---|
| 0 | 3 | i = 0 | i = 3, by the 5 |
| 1 | 1 | i = 1 | i = 2, by the 2 |
| 2 | 2 | i = 2 | i = 3, by the 5 |
| 3 | 5 | i = 3 | never |
| 4 | 4 | i = 4 | never |
Each index is pushed once and popped at most once, because once it is popped it never comes back. So across the whole walk the body of the while loop runs at most n times in total, not n times per item. Here it ran 3 times for 5 items. The while test runs once more than the pops at each item (the check that stops it), so 3 + 5 = 8 checks in all. At most 2n checks and n pushes: O(n) time.
One item can still pop many. In [5, 4, 3, 2, 1, 6] the 6 pops five indexes in one go. But those five were pushed one per step and are gone afterward, so a big pop is paid for by the pushes before it. Counting the total over the whole walk, instead of the worst single step, is the amortized analysis module 2 used for append. The stack itself can hold every index, for example when the list only falls and nothing is ever popped: O(n) extra space.
In the stack version of next greater element, a while loop sits inside the for loop, and one item can pop many. What is the total running time on a list of n items?
Choose one answer, then check.
Same walk, different notebook
The next two problems are this walk. What changes is what goes on the stack and where the answer is written. One detail first: "bigger" means strictly bigger. The test nums[stack[-1]] < x pops only items strictly smaller than x, so an equal item stays on the stack and keeps waiting. See what happens when the test lets equal items go.
This version adds one character to the while test: <= instead of <.
def next_greater(nums):
answer = [-1] * len(nums)
stack = []
for i, x in enumerate(nums):
while stack and nums[stack[-1]] <= x:
j = stack.pop()
answer[j] = x
stack.append(i)
return answer
What does next_greater([3, 1, 3, 5]) return?
Choose one answer, then check.
First change: values and a dict. In the first problem the values are distinct, and the answers are wanted for a separate list of queries, in the queries' order. Distinct values mean each value names exactly one position. So the stack can hold the values themselves, and each answer can go into a dict keyed by the value it answers. Then each query is one dict lookup.
A value that is never popped never met a bigger value, so it has no entry in the dict, and its lookup needs the default -1. The walk is O(n) and the lookups add O(m) for m queries.
Second change: indexes, because the answer is a distance. Daily temperatures asks, for each day, how many days until a strictly warmer one. The wait is the distance between two days, so the stack must hold indexes: from index j you get the temperature temps[j] and the wait i - j. A day that never sees a warmer day waits 0, so start the answer list at all zeros. An equal day is not warmer, so the pop test stays strict.
The days still on the stack when the walk ends kept the 0 they started with, which is their answer. On [70, 68, 72, 71, 75], the 72 pops the 68 and the 70, the 75 pops the 71 and the 72, and only the 75 is left. Each index is pushed once and popped at most once, so it is O(n) again.
The largest rectangle under a bar chart
Now the capstone, a hard problem built on the same stack. A histogram here is a bar chart: bars of width 1, side by side, where heights[i] is the height of bar i. We want the largest rectangle that fits under the bars, standing on the ground. A rectangle that covers a run of neighboring bars can be as tall as the shortest bar in that run, and no taller.
Fix the height
The brute force tries every run of bars, keeping the shortest height as each run grows: about n2/2 runs, O(n2). The better idea is to fix the height instead of the ends. Pick a bar k and ask how wide a rectangle exactly as tall as bar k can be. It stretches left and right over bars at least as tall, until it meets a shorter bar on each side. Call those two bars left and right, using -1 when no shorter bar is on the left and n, the number of bars, when none is on the right. The rectangle covers the bars strictly between them:
- width =
right - left - 1 - area =
heights[k] * width
The answer is the largest of these n areas, one per bar. Why is one rectangle per bar enough? Every rectangle under the bars has a shortest bar k in its run, so it is no taller than bar k, and it fits inside the widest rectangle of height heights[k] around bar k. So the best rectangle is always one of the n candidates.
Take [3, 5, 4, 1] and bar 2, of height 4. The nearest shorter bar on its left is bar 0 (height 3), and the first shorter bar on its right is bar 3 (height 1). So width = 3 − 0 − 1 = 2 and area = 4 × 2 = 8. In the drawing, each # or = is one square of a bar, and the numbers on the left count the height. The = squares are that rectangle: 4 tall over bars 1 and 2.
5 #
4 = =
3 # = =
2 # = =
1 # = = #
bar 0 1 2 3
The rectangle stops at bar 0 and bar 3 because both are shorter than 4. The top square of bar 1 stays out, because the rectangle is only as tall as bar 2. Work out the other three bars on paper.
Take the histogram [3, 5, 4, 1]. For each bar, find its left edge (the nearest strictly shorter bar on its left, or -1), its right edge (the first strictly shorter bar on its right, or 4, one past the last bar), the width right - left - 1, and the area height * width. Then give the largest area. Work it out on paper, then reveal the steps one at a time.
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.
One stack finds both edges
The right edge is next greater element turned upside down. Each bar waits for the first shorter bar, so the stack pops while the top bar is taller than the new bar, and the heights on the stack never fall from bottom to top. Flip one comparison and you have it. Write that version first.
Write next_smaller_index(heights). For each bar it returns the index of the first strictly shorter bar to its right, or len(heights) if there is none (one past the last bar, which is exactly the right edge the rectangle formula wants). Use one walk and a stack of waiting indexes. Then press Watch it run to see the stack.
raise NotImplementedError, then press Run tests. Each check says what it expects.The left edge comes free. When bar i pops a bar, call the popped bar top and look at the bar now on top of the stack, left. When top first arrived, it popped every taller bar sitting above left, and those bars had already popped the taller bars before them. So every bar between left and top is taller than top, and left is not, or top would have popped it too. The bar below a popped bar is its left edge (equal heights add one wrinkle, covered after the trace). If the stack is empty after the pop, every bar before top is taller, and left is -1.
One extra bar of height 0 at the end pops every bar still waiting, so every bar with a height above 0 gets measured. Without it, a bar that never meets a shorter bar, like every bar of [1, 2, 3], is never popped. In code, heights + [0] builds a new list, the heights with a 0 on the end, and leaves heights itself unchanged.
The trace walks [1, 3, 2] plus the extra bar. Each time a bar is popped it prints three numbers: the bar, its left edge, its right edge. Line 6 makes a choice in one line: stack[-1] if stack else -1 gives stack[-1] when the stack has an item, and -1 when it is empty. The arrow i sits one past the last bar when it reaches the extra 0. Before you step through, guess which bar has the largest rectangle.
def bar_edges(heights):stack = []for i, h in enumerate(heights + [0]):while stack and heights[stack[-1]] > h:top = stack.pop()left = stack[-1] if stack else -1print(top, left, i)stack.append(i)
(nothing printed yet)Equal heights need one more thought. The stack pops only strictly taller bars, so equal bars wait side by side, and the bar below a popped bar can be its equal rather than a shorter bar. Take [2, 2]. The extra 0 pops bar 1 first, with bar 0 below it, so it measures width 2 − 0 − 1 = 1 and area 2: too narrow. Then it pops bar 0 with nothing below, width 2 − (−1) − 1 = 2, area 4. The last of the equal bars to be popped reaches the true left edge, so the best area is still found.
To recap: one walk, one stack of waiting bars whose heights never fall. The bar that pops a bar is its right edge, the bar below it is its left edge, and the extra 0 makes sure every bar is measured. Turning edges into areas is the last step, and it is yours.
This module's problem list has one more from this family: online stock span (LeetCode 901). Its stack holds a price and a span for each day, and its pop test is <=, because a day at the same price counts toward the span. Match the pop test to the question.
Last, say it the way you would in the room.
Explain, as you would to an interviewer before typing, how you would find for each day the number of days until a warmer day. Cover the walk, the notebook, the promise and the cost, and answer the follow-up you expect: "there is a while loop inside your for loop, so isn't this O(n2)?"
Saved in this browser as you type.