Keep a stack in increasing or decreasing order to find the next greater or smaller value, spans and the largest rectangle in one pass.
A savings app shows the daily price of an investment fund as a chart. Next to each day, the app shows a span. The span is the number of days in a row, counting back from that day and including it, with a price at or below that day's price. A long span means the price is at a high for the period.
Your team lead says: "A fund has years of daily prices. Show the span for every day, and update it when a new day arrives."
You have met this shape before. In a warm-up of the first stack lesson, a stack answered "how many hours until a slower response". This lesson names the idea, makes it work in both directions, and shows what it costs.
The idea is to remember only what can still matter. An old price that is no higher than a later price can never end a span for any day after that later price. So forget it. What is left is a stack of prices that fall from bottom to top, and that is all a span needs.
Picture a row of flats along a street, all facing a lake on the right. A flat has a lake view when no flat to its right is taller. When a new, taller flat is built at the right end, every shorter flat that had a view loses it.
The flats with a view are always in order, from the tallest on the left to the shortest on the right. A new flat takes the view away from the flats that are shorter than it, one after another from the right. Then it joins the line.
The flats that kept their view are a stack. The newest flat is on top, and a taller newcomer removes the shorter flats from the top.
A flat keeps its view while nothing taller is to its right. A taller new flat takes views away, so the flats with a view form a stack.
A monotonic stack is an ordinary stack with a rule about its order. It is stored as an array or a linked list, as in the first lesson. The rule is kept by the code that pushes: before a push, it pops whatever would break the order.
Step by step: A falling stack in memory. The animated player loads in your browser.
Four words come up in every problem in this lesson:
Predict what happens
Q A stack that falls from bottom to top holds 90, 70 and 40. The value 80 arrives. Which values leave the stack?
Answer: B
The pops continue while the top is lower than 80. The 40 is lower, then the 70 is lower, but the 90 is not. The stack ends as 90, 80, and it still falls.
Every monotonic stack follows one rule. When a value arrives, pop while the top breaks the order, then push the new value. Watch it on a stack that falls from bottom to top. Predict which values leave before the player shows it.
Step by step: A value of 80 arrives. The animated player loads in your browser.
A new value pops every lower value on top, then goes on top. Here 80 pops 40 and 70 and stays under 90. The stack still falls.
Predict what happens
Q A stack falls from bottom to top: 90, 70, 40. The value 95 arrives, and the rule is "pop while the top is lower". How many values are popped, and what is on the stack afterwards?
Answer: C
A value higher than everything pops everything. The 40, the 70 and the 90 are all lower than 95, so all three leave, and 95 is alone on the stack.
Take the daily prices [50, 44, 60, 52, 52, 41, 47, 58]. For each day, find the next day with a strictly higher price. Read the days from left to right. A stack holds the days that are still waiting for a higher price, and their prices never rise from bottom to top.
When a new day arrives, it pops every waiting day with a lower price. It is the answer for each of them. Then it waits itself.
| Day | Price | Days popped (their answer) | Stack after (days) |
|---|---|---|---|
| 0 | 50 | none | 0 |
| 1 | 44 | none | 0, 1 |
| 2 | 60 | day 1: 60, day 0: 60 | 2 |
| 3 | 52 | none | 2, 3 |
| 4 | 52 | none | 2, 3, 4 |
| 5 | 41 | none | 2, 3, 4, 5 |
| 6 | 47 | day 5: 47 | 2, 3, 4, 6 |
| 7 | 58 | day 6: 58, day 4: 58, day 3: 58 | 2, 7 |
Days 2 and 7 are still waiting at the end, so they have no higher day after them. Their answer is -1. The answers are [60, 60, -1, 58, 58, 47, 58, -1].
The stack holds positions, not only prices. Positions are what you need when the answer is a distance. A price is always read back through its position: prices[top].
Exercise · Find the bug: An answer that is a position. This function should give, for each day, the number of days until a strictly higher price (0 if there is none). On some inputs a few answers are too big. Which line is wrong?
def days_until_higher(prices):
n = len(prices)
result = [0] * n
stack = []
for i in range(n):
while stack and prices[stack[-1]] < prices[i]:
j = stack.pop()
result[j] = i
stack.append(i)
return resultNow read the same stack the other way. For a span, you want the nearest earlier day with a strictly higher price. After a new day has popped every day at or below its price, the day left on top is exactly that day.
The span is the distance to it, and an empty stack means that no earlier day is higher, so the span reaches the first day.
| Day | Price | Days popped | Stack after (days) | Span |
|---|---|---|---|---|
| 0 | 50 | none | 0 | 1 |
| 1 | 44 | none | 0, 1 | 1 |
| 2 | 60 | 1, 0 | 2 | 3 |
| 3 | 52 | none | 2, 3 | 1 |
| 4 | 52 | 3 | 2, 4 | 2 |
| 5 | 41 | none | 2, 4, 5 | 1 |
| 6 | 47 | 5 | 2, 4, 6 | 2 |
| 7 | 58 | 6, 4 | 2, 7 | 5 |
The spans are [1, 1, 3, 1, 2, 1, 2, 5]. On day 4 the price is 52 again, and it pops day 3, which also costs 52. Equal prices are inside a span, so this stack pops on less than or equal.
A span looks left. A price pops earlier prices at or below it, and the span runs back to the price left on top.
The two stacks above use different comparisons. The next greater value pops on <, so an equal price waits. The span pops on <=, so an equal price is removed. The choice changes the answer, and it is always a decision about the problem.
On the same prices, the next strictly greater price for day 3 (52) is 58, because day 4 is equal and waits. The next price that is greater or equal is 52, the price of day 4.
| Question | Pop condition | Equal values | Answers for the prices above |
|---|---|---|---|
| Next strictly greater | top < new |
wait | [60, 60, -1, 58, 58, 47, 58, -1] |
| Next greater or equal | top <= new |
are matched | [60, 60, -1, 52, 58, 47, 58, -1] |
Say out loud which one the problem wants. "Strictly higher" asks for <, and "higher or the same" asks for <=. When the problem looks for a lower value instead, as a markdown does, both flip: > and >=.
Exercise · Put it in order: The next greater loop. Arrange the lines into a function that returns, for each value, the next strictly greater value to its right, or -1 when there is none.
def next_greater(nums):
result = [-1] * len(nums)
stack = []
for i in range(len(nums)):
while stack and nums[stack[-1]] < nums[i]:
result[stack.pop()] = nums[i]
stack.append(i)
return result
while stack and nums[stack[-1]] <= nums[i]:Predict what happens
Q The prices are 4, 4 and 5. You find the number of days until a strictly higher price, and you pop on less than. What is the answer for day 0?
Answer: B
Day 1 costs 4, the same as day 0, so it is not strictly higher. The pop on less than leaves day 0 waiting until day 2, which costs 5. The distance is 2.
There is a loop inside the loop. A single new value can pop many days. So it looks as if the cost could be n × n.
It cannot, and the reason takes three sentences. Every day is pushed exactly once, when it arrives. A day can be popped only once, because after that it is gone. So the number of pops is never more than the number of pushes.
In the next-greater table there are 8 pushes and 6 pops, and 2 days are still on the stack at the end. 8 pushes = 6 pops + 2 days left. The work for the whole pass is about 14 steps, however the prices are shaped.
The pops of one new value can be many, and the pops of the next can be none. The average is at most one pop for each value. That is amortised O(1) for each day, and O(n) for the pass.
Exercise · Predict the output: Count the pops. This loop finds the next strictly higher price, and counts every pop. What does it print: the total number of pops, and the number of days left on the stack?
prices = [4, 4, 2, 6, 3, 3, 5]
stack = []
pops = 0
for i in range(len(prices)):
while stack and prices[stack[-1]] < prices[i]:
stack.pop()
pops += 1
stack.append(i)
print(pops, len(stack))If the schedule repeats, as demand does over a day, the last slot is followed by the first. Walk the list twice: the indexes 0 to 2n - 1, reading the item at i % n. Push only on the first lap, so that each item waits once. The second lap lets the early items answer the late ones.
Take the demand [30, 80, 20, 60, 10, 50]. The slot 5 has demand 50, and nothing after it on the first lap is higher. On the second lap, slot 0 reads 30, then slot 1 reads 80, and 80 answers slot 5. The answers are [80, -1, 60, 80, 50, 80]: only the highest slot has no answer.
Some problems ask you to remove items to make the result as small as possible. Strike out 3 digits of 3815264 to make the smallest number. A larger digit right before a smaller one makes the number bigger, so remove it.
Keep the digits on a stack. When a smaller digit arrives, pop larger digits while removals remain.
| Digit read | Digits popped | Removals left | Stack after |
|---|---|---|---|
| 3 | none | 3 | 3 |
| 8 | none | 3 | 38 |
| 1 | 8, 3 | 1 | 1 |
| 5 | none | 1 | 15 |
| 2 | 5 | 0 | 12 |
| 6 | none | 0 | 126 |
| 4 | none | 0 | 1264 |
The result is 1264. If removals are left when the digits run out, the stack never falls from bottom to top. Its largest digits are at the end, so cut them off.
Exercise · Break it: Find the input that keeps too many digits. This function removes exactly k digits to make the smallest number, using a stack and a budget. Find an input where it gives the wrong answer.
def remove_digits(digits, k):
stack = []
for d in digits:
while stack and k > 0 and stack[-1] > d:
stack.pop()
k -= 1
stack.append(d)
return stackPredict what happens
Q You strike out 1 digit of 1423 to make the smallest number, with a stack and a budget of removals. What is the result?
Answer: B
The digits 1 and 4 rise, so they wait. The 2 is smaller than the 4, so the 4 is popped and the budget is used up. Then the 3 goes on, and the stack reads 1, 2, 3.
A bar chart has bars of heights [2, 5, 3, 3, 6, 4, 1]. Find the rectangle with the largest area that fits under the bars. Each bar decides one rectangle: the widest one in which that bar is the lowest. It stretches left and right until it meets a lower bar.
A stack of bars that rise from bottom to top finds both edges. The bar under a bar on the stack is its left edge. The bar that pops it is its right edge.
Close the chart with a bar of height 0, so that every bar is popped.
| Bar read | Height | Bars popped (height × width = area) | Stack after (bars) |
|---|---|---|---|
| 0 | 2 | none | 0 |
| 1 | 5 | none | 0, 1 |
| 2 | 3 | bar 1: 5 × 1 = 5 | 0, 2 |
| 3 | 3 | bar 2: 3 × 2 = 6 | 0, 3 |
| 4 | 6 | none | 0, 3, 4 |
| 5 | 4 | bar 4: 6 × 1 = 6 | 0, 3, 5 |
| 6 | 1 | bar 5: 4 × 2 = 8; bar 3: 3 × 5 = 15; bar 0: 2 × 6 = 12 | 6 |
| end | 0 | bar 6: 1 × 7 = 7 | (the closing bar) |
The largest area is 15: height 3 across the bars from position 1 to position 5. Ties do not matter here. Popping on > or on >= gives the same largest area. They would matter if you counted rectangles instead, as in the sum of the minimum of every run.
Each bar decides the widest rectangle where it is lowest. A stack of rising bars finds both edges, and a closing 0 pops the rest.
Every operation touches the top, so the stack is as cheap as in the first lesson. The new part is the cost of answering for a whole list.
| Operation | Monotonic stack | Plain stack | Scanning from each item |
|---|---|---|---|
| Push a value | O(1), after its pops | O(1) | Not used |
| Pop the top | O(1) | O(1) | Not used |
| Peek at the top (the nearest candidate) | O(1) | O(1) | Not used |
| Search: next greater value for one item | O(n): the pass must reach the answer | O(n): look at every item | O(n): scan to the right |
| Answers for every item in a list of n | O(n) in all: each item is pushed and popped once | Not possible without scanning | O(n^2) in the worst case |
| Read any item below the top | O(k) for the item k places down | O(k) | Not used |
The stack does not make a single answer cheaper. It makes all n answers cost n steps together, because the work of one item is reused by the next.
Now drive the stack yourself. A value that arrives is drawn as the pops it causes and one push. Use Pop until the top is no longer lower than your value, then Push it, and read the step counter.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the rule yourself. The lab gives you a WaitingStack class. You write add, top, size, total_removed and to_list.
add is the whole idea. It takes a value, removes every value on top that is lower, and returns the removed values in the order they left, top first. Then it puts the new value on top. An equal value stays.
You built an array stack in the first lesson, so here you may use your language's list as the stack. Four rules keep the class correct after every call:
add returns exactly the values it removed, top first.total_removed counts every removal ever made, and it is never more than the number of add calls.-1 and changes nothing.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a monotonic stack when each item needs the nearest greater or smaller item on one side. Examples are the next warmer day, the previous higher price and the nearest taller bar. It also fits the questions built from those edges: spans, the largest rectangle, the sum of minimums of every run, and removing items to make a result smallest.
The signal is "for every item, find the nearest ... that is bigger", together with a list large enough that scanning from each item would be too slow.
Do not use it when an item must leave because it is old, not because something bigger arrived. The maximum of every window of k days needs a structure that drops items from the front too: a deque, which comes in the queue lessons.
Do not use it when the values change after they were read. A stack remembers only what was true when each value arrived. And do not reach for a single stack for the k-th greater value: it gives the nearest one only.
You want the number of days until a strictly higher price, but you write while stack and prices[stack[-1]] <= prices[i]. Equal prices are then matched too early. On prices = [4, 4, 5], day 0 gets 1 instead of 2: the output is [1, 1, 0], and the correct one is [2, 1, 0]. Decide the tie rule before you write the condition.
Popping on less than or equal answers day 0 too early: it gets 1 instead of 2. For a strictly higher price, equal prices must wait.
In while prices[stack[-1]] < x and stack:, the top is read before the stack is checked. When a value pops everything, the stack is empty, and each language reacts in its own way:
IndexError.stack[size - 1] with size 0 throws ArrayIndexOutOfBoundsException.back() on an empty vector is undefined behaviour.undefined < x is false, so the loop ends quietly.Write while stack and ..., so that the check comes first in every language.
In the largest rectangle, the bars still on the stack at the end are never popped, so they never give an area. On heights = [1, 2, 3] the loop pops nothing, and the answer stays 0 instead of 4. Add a bar of height 0 after the last one, as in for i in range(n + 1).
For each item, scan to the right until a bigger value appears. It is correct, but when the values fall the scans are long. With prices falling over 100,000 days, that is about 5 × 10^9 steps: for i in range(n): for j in range(i + 1, n): .... The stack does the same job in about 2 × 10^5.
< makes equal values wait, and <= matches them. A maximum does not care. A count needs one strict side.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The rule
Q1/2 A stack that falls from bottom to top holds 90, 70 and 40. The value 80 arrives, and the rule is "pop while the top is lower, then push". What does the stack hold afterwards?
Answer: B
The 40 and the 70 are lower than 80, so both are popped. The 90 is not lower, so the pops stop. Then 80 goes on top, and the stack still falls.
Q2/2 You want, for every day, the number of days until a strictly higher price. Which pop condition do you use, with top the price on the stack and new the price that arrives?
Answer: A
A strictly higher price needs <. With <=, an equal price would answer the day too early. Equal prices must wait for a price that is really higher.
Checkpoint · The cost
Q1/2 Why is a whole pass with a monotonic stack O(n), although a while loop sits inside the for loop?
Answer: B
One new value can pop many values, but each value can be popped only once. Over the whole pass the number of pops is at most n, so the loops add up to O(n).
Q2/2 A pass over a list pushes 12 values and pops 9 of them. How many values are on the stack at the end?
Answer: C
Every pushed value is either popped or still on the stack. So 12 pushes = 9 pops + 3 values left. The three values left have no answer, such as no higher day after them.
Checkpoint · Spans and lists
Q1/3 The daily prices are 5, 5, 3 and 7. The span of day 1 counts the days in a row, back from day 1 and including it, with a price at or below day 1's price. What is it?
Answer: B
Day 1 costs 5, and day 0 costs 5 too. Equal counts, so the stack pops day 0 on less than or equal, and the span runs back to the first day: 2 days.
Q2/3 A schedule is circular, and the demand is 3, 1, 2. What is the next higher demand for the last slot, which has 2?
Answer: C
After the last slot comes the first. Slot 0 has demand 3, which is higher than 2, so the answer is 3. Only the second lap of the pass finds it.
Q3/3 You strike out 2 digits of 1432 to make the smallest number, using a stack and a budget of removals. What is the result?
Answer: C
The 4 is larger than the 3 that follows it, so it is popped. Then the 3 is larger than the 2, so it is popped too. The budget is used up, and the stack reads 1, 2.
Checkpoint · The rectangle and the limits
Q1/3 In the largest rectangle under a bar chart, the loop runs to n + 1 and the last bar has height 0. What does it do?
Answer: A
A height of 0 is lower than every bar. The pops continue until the stack is empty, and each popped bar gives its height times its width. Without it, the last bars are never measured.
Q2/3 The bars have heights 2, 1 and 2. What is the largest area of a rectangle that fits under them?
Answer: C
The lowest bar, height 1, can stretch over all three bars: 1 × 3 = 3. A rectangle of height 2 fits over one bar only, so its area is 2.
Q3/3 Which job is the best fit for a monotonic stack?
Answer: B
The nearest greater value on one side is what the stack gives. A window needs items to leave from the front, which is a deque. A third highest needs more than the nearest one, and a lookup by date needs an index or a map.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.