Monotonic stacks
Solve next-greater-element and histogram problems in O(n) with a monotonic stack.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
A monotonic stack keeps its elements in increasing or decreasing order by popping anything that would break the order before pushing. Each element is pushed and popped at most once, so the whole scan is O(n). It answers next-greater, previous-smaller and histogram questions that look quadratic.
Explained simply
Imagine people standing in a line, each a different height, all looking to the right. For each person you want to know who is the first taller person they can see. Checking every pair works, but for a long line that is very slow.
A monotonic stack solves this in one pass. Monotonic means always going one way: the values in the stack are always decreasing (or always increasing) from bottom to top. When a new value arrives that would break that order, you pop values until the order is fine again, then push the new one.
The useful part is what popping means. When a taller person arrives and you pop a shorter one, the taller person is exactly the answer for the one you popped: their first taller person to the right. Each value gets its answer at the moment it leaves the stack.
Every element is pushed once and popped at most once, so the whole scan takes time proportional to the length of the array, even though the code has a loop inside a loop.
Press Play on a diagram to walk through it one step at a time.
- 1Read x
Next array value.
- 2Pop smaller
Each popped item has found its next greater: x.
- 3Push x
Stack stays decreasing.
- 4Advance
Leftovers have no next greater.
- Back to step 1
- For each i, scan right until a bigger value
- O(n^2) time in the worst case
- O(1) extra space
- Simple but too slow for 10^5 items
- One left-to-right pass
- Each index pushed and popped once
- O(n) time
- O(n) extra space
In depth
Which stack order answers which question
Four questions come up again and again: for each element, find the next greater, next smaller, previous greater or previous smaller element. They all use the same loop with a different comparison.
To find the next greater element, scan left to right and keep the stack decreasing: pop while the top is smaller than the current value, and each popped element's answer is the current value. For the next smaller element, keep the stack increasing and pop while the top is larger.
Previous answers come for free from the same scan. After popping, whatever is left on top is the nearest element to the left that survived. With a decreasing stack, that top is the previous greater (or equal) element; with an increasing stack it is the previous smaller (or equal) one. You can also scan from right to left to turn next into previous.
Store indexes, not values. With an index you can read the value, compute a distance such as days to wait, or a width in a histogram.
- Next greater: decreasing stack, pop while top < x
- Next smaller: increasing stack, pop while top > x
- Previous answer: the top after popping
- Store indexes for distances and widths
Why the nested loop is still O(n)
The inner while loop can pop many elements in one step, so a single iteration of the outer loop may cost O(n). It is tempting to multiply and say O(n^2). But count operations over the whole run instead of per step: each index is pushed exactly once, and an index can only be popped after it was pushed, so there are at most n pops in total. The whole algorithm does at most 2n stack operations plus n comparisons that end the inner loop, which is O(n).
This way of counting is called amortised analysis: an expensive step is paid for by earlier cheap steps. It is the same argument that makes dynamic array appends O(1) on average.
The extra space is O(n) in the worst case, for example a fully decreasing array when you look for the next greater element: nothing is ever popped until the end.
Largest rectangle in a histogram
Given bar heights, find the largest rectangle that fits under them. For each bar, the widest rectangle of exactly its height reaches left to just after the previous smaller bar and right to just before the next smaller bar. An increasing stack finds both in one pass.
Scan left to right with a 0 added at the end. While the current bar is lower than or equal to the bar on top of the stack, pop it: the current index is its right boundary, and the new top of the stack, or -1 if the stack is empty, is its left boundary. Its width is i - left - 1 and its area is height times width. The added 0 forces every remaining bar off the stack at the end.
The result is O(n) time and O(n) space, compared with O(n^2) for checking every pair of boundaries. The same routine, run row by row on a 0/1 matrix where each row's heights count consecutive 1s above, solves maximal rectangle in O(rows times columns).
- 1i=1, height 1
Pop 2: width 1, area 2
- 2Push 5 and 6
Stack heights: 1 5 6
- 3i=4, height 2
Pop 6: width 1, area 6
- 4Still at i=4
Pop 5: width 2, area 10
- 5Sentinel 0 at i=6
Pop 3, 2, 1: areas 3, 8, 6
- 6Answer
Largest area is 10
Equal values and circular arrays
Duplicates are where monotonic stack solutions break. Decide for each problem whether equal values should pop (use <= or >=) or stay (use < or >). For next greater, popping only on strictly smaller values means an equal later value is not counted as greater, which is usually what you want.
When you count something over all subarrays, such as the sum of subarray minimums, an equal minimum can be counted twice. The standard fix is asymmetric: use strictly smaller on one side and smaller or equal on the other, so each subarray is assigned to exactly one of its tied minimums.
For a circular array, where the search may wrap past the end, loop i from 0 to 2n - 1 and read nums[i % n]. Push indexes only in the first pass so each still enters the stack once. That keeps the scan O(n).
- Decide strict vs non-strict comparison up front
- Counting problems: strict on one side, non-strict on the other
- Circular: iterate 2n times with i % n
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Maintain an increasing or decreasing stack~40m
- 2Find the next greater element~40m
- 3Solve daily temperatures~40m
- 4Find the largest rectangle in a histogram~40m
Key points
- Total time O(n): every index is pushed once and popped at most once.
- Decreasing stack finds next greater; increasing stack finds next smaller.
- Store indexes so you can compute distances such as days until warmer.
- Largest rectangle in a histogram is O(n) with an increasing stack.
Key terms
Tap a card to flip it. 0/3 known
Examples
def daily_temperatures(t): # O(n)
ans = [0] * len(t)
stack = [] # indexes, temperatures decreasing
for i, temp in enumerate(t):
while stack and t[stack[-1]] < temp:
j = stack.pop()
ans[j] = i - j
stack.append(i)
return ans
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76]))
# [1, 1, 4, 2, 1, 1, 0]Next greater element in a circular array
Input: 1 2 1. For the last 1, the search wraps around and finds 2, so the answer is 2 -1 2. Step 1: loop i over 2n positions and use nums[i % n]. Step 2: pop every index whose value is smaller than the current value and set its answer. Step 3: push indexes only during the first pass. Indexes still on the stack at the end, here only the 2, have no greater element. O(n) time, O(n) space.
def next_greater_circular(nums):
n = len(nums)
ans, stack = [-1] * n, [] # indexes, values decreasing
for i in range(2 * n):
x = nums[i % n]
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x
if i < n:
stack.append(i)
return ans
print(next_greater_circular([1, 2, 1])) # [2, -1, 2]Largest rectangle in a histogram
Heights 2 1 5 6 2 3. Step 1: append a 0 so all bars get popped at the end. Step 2: keep indexes with increasing heights. Step 3: when a bar is lower than or equal to the top, pop the top; its right edge is i and its left edge is the new top. Step 4: track the best area. The bars of height 5 and 6 give the answer 5 times 2 = 10.
def largest_rectangle(h): # O(n) time, O(n) space
stack, best = [], 0 # indexes, heights increasing
for i, x in enumerate(h + [0]): # the 0 flushes the stack
while stack and h[stack[-1]] >= x:
height = h[stack.pop()]
left = stack[-1] if stack else -1
best = max(best, height * (i - left - 1))
stack.append(i)
return best
print(largest_rectangle([2, 1, 5, 6, 2, 3])) # 10Quick reference
- Each index is pushed once and popped at most once: O(n) time, O(n) space
- Next greater: keep values decreasing, pop while nums[top] < x
- Next smaller: keep values increasing, pop while nums[top] > x
- After popping, the top is the nearest surviving element to the left
- Histogram: width = i - stack[-1] - 1, or i if the stack is empty
- Circular arrays: loop 2n times with i % n, push only when i < n
- Subarray counting with ties: strict on one side, non-strict on the other
Common mistakes
- Using < versus <= inconsistently, which mishandles equal values.
- Calling the nested while loop O(n^2) and abandoning a correct solution.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Return the next greater element for every position, or -1 if there is none.
- Exercise 2medium
Stock span: for each day, count how many consecutive days up to and including today had a price less than or equal to today's.
- Exercise 3hard
Return the sum of min(sub) over every contiguous subarray, modulo 10^9 + 7, in O(n). For 3 1 2 4 the answer is 17.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I recognise a monotonic stack problem?
- Look for phrases like next greater, previous smaller, how many days until, or the nearest bigger value, especially when the brute force is O(n^2). Histogram, rain water and stock span problems are classic cases.
- What is the difference between a monotonic stack and a monotonic deque?
- A monotonic stack only works at one end and answers nearest greater or smaller questions. A monotonic deque also removes from the front, which lets it track the maximum or minimum of a sliding window.
- Should the stack hold values or indexes?
- Usually indexes. You can always read the value from the array, and indexes let you compute distances and widths.