Sub topic 16
Monotonic stacks and next-greater-element problems
This chapter assumes you can write a stack with a Python list, read Big-O notation, and use while loops. You have already seen push, pop, and peek. Here you will add one rule to the stack: keep its contents in sorted order.
The problem
Given a list of numbers, find for each element the next element to its right that is larger. If none exists, answer -1.
For [2, 1, 5, 3] the answer is [5, 5, -1, -1].
The direct approach checks every later element for each position. That takes O(n²) time. A monotonic stack solves it in O(n).
What "monotonic" means
A monotonic stack keeps its items in one order from bottom to top, either always increasing or always decreasing. Before you push a new item, you pop every item that would break the order. Those popped items have just met the value that answers their question.
For next-greater-element, the stack holds indices whose answer is still unknown. Their values decrease from bottom to top. When a larger value arrives, it is the answer for every smaller value on top of the stack.
The code
def next_greater(nums):
result = [-1] * len(nums)
stack = [] # indices whose next greater value is not found yet
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
result[stack.pop()] = x
stack.append(i)
return result
print(next_greater([2, 1, 5, 3])) # [5, 5, -1, -1]The stack stores indices, not values. An index lets you write the answer into the right slot of result and also look up the value with nums[index]. Indices left on the stack at the end keep their default -1.
Tracing the run
For [2, 1, 5, 3]:
| Step | x | Stack before (values) | Action | Stack after (values) |
|---|---|---|---|---|
| 1 | 2 | empty | push index 0 | 2 |
| 2 | 1 | 2 | 1 is not larger than 2, push | 2, 1 |
| 3 | 5 | 2, 1 | pop 1 and 2, both get 5, push | 5 |
| 4 | 3 | 5 | 3 is not larger than 5, push | 5, 3 |
Indices 2 and 3 remain, so they keep -1.
Why it is O(n)
The while loop sits inside the for loop, which can look like O(n²). It is not. Each index is pushed exactly once and popped at most once. The total number of pops across the whole scan is at most n, so the total work is O(n). Extra space is O(n) for the stack in the worst case, such as a strictly decreasing input.
Common errors
- Storing values instead of indices. You then cannot tell which result slot to fill, especially with duplicates.
- Wrong comparison.
<finds the next strictly greater value. Using<=would also pop equal values, which finds the next greater-or-equal one. Pick the one the problem asks for. - Forgetting the leftovers. Items still on the stack have no answer. Initialize
resultwith-1, or fill them after the loop. - Popping from an empty stack. Always check
stack and ...before readingstack[-1].
Variations
Flip the comparison to > to find the next smaller element. Scan from right to left to find the previous greater element. Next-greater problems appear in daily temperatures, stock span, and largest rectangle in a histogram.
Exercise
Change next_greater so it returns the next smaller element for each position. What do you change, and what is the answer for [4, 5, 2, 1]?
Show answer
Change the comparison in the while loop from nums[stack[-1]] < x to nums[stack[-1]] > x. The answer is [2, 2, 1, -1].
Exercise
Why is next_greater O(n) even though a while loop runs inside a for loop?
Show answer
Each index is pushed once and popped at most once, so the total number of pops over the whole scan is at most n. The inner loop's work adds up to O(n), not O(n) per element.