Monotonic Stacks & Queues
Next greater elements, sliding-window maxima and the largest rectangle, in linear time.
For each day of the year, how many days until a warmer one? Checking every later day costs . A stack that keeps only the days still waiting for their answer finds all of them in one pass, and the same idea finds sliding-window maxima, the water trapped between bars and the largest rectangle under a histogram, each in .
What you’ll learn
- Compute the next (or previous) greater or smaller element of every index in with a monotonic stack, and prove the bound by counting pushes and pops.
- Choose strict or non-strict comparisons when values repeat, and adapt the loop to previous elements and circular arrays.
- Solve spans, waiting times, trapped rain water, histogram rectangles and the sum of subarray minimums with nearest greater or smaller boundaries.
- Maintain sliding-window maxima with a monotonic deque in total time, and prove its invariant.
- Recognize "nearest greater or smaller" and "window maximum or minimum" structure in a problem statement.
Next greater element: from O(n²) to O(n)
For each index of an array , the next greater element is at the smallest with , or nowhere (). The brute force scans right from each : in the worst case, for instance on a decreasing array, where every scan runs to the end.
The waste is in rescanning elements that can no longer be anyone's answer. Scan left to right instead, and keep a stack of the indices still waiting for their answer. Their values never increase from bottom to top: if a waiting element were smaller than a later waiting one, the later one would already have answered it. When arrives it is the answer for every waiting index with a smaller value, and those are exactly the ones on top. Pop them, record for each, then push .
def next_greater(a):
n = len(a)
ans = [-1] * n # -1: no greater element to the right
stack = [] # indices still waiting; values never increase upward
for i, x in enumerate(a):
while stack and a[stack[-1]] < x:
ans[stack.pop()] = i # x is the first greater element after it
stack.append(i)
return ansA monotonic stack: from bottom to top its values never increase. A popped index's answer is the index that popped it; the indices still on the stack at the end have no greater element to their right.
On the array , how many pops does next_greater perform in total?
Show the answer
6 pops
Each index is popped at most once, when its next greater element arrives: 5 pops the 2; 8 pops 3, 4, 5 and 6; the final 4 pops the 1. That makes 6. The indices of 8, 7 and the final 4 stay on the stack, because nothing greater follows them: .
Why it is linear, and why it is right
Invariant. Before index is processed, the stack holds exactly the indices with no greater element among , in increasing order of index; their values never increase from bottom to top.
Pops are correct. If is popped at step , then , while for every between them by the invariant. So is the first greater element after .
The invariant survives. Popping stops at the first index with , and everything below it is at least as large, so the indices that remain are exactly those still waiting after . Pushing keeps the values non-increasing.
Linear time, by the aggregate method. Each index is pushed once and popped at most once, and the last index pushed is never popped, so the inner loop runs at most times over the whole run:
| For each , find … | Pop while | Answer |
|---|---|---|
| the next greater element | each popped index gets | |
| the next greater-or-equal element | each popped index gets | |
| the next smaller element | each popped index gets | |
| the previous greater element | gets the top left after popping | |
| the previous smaller element | gets the top left after popping | |
| the next greater element, circularly | , for | each popped index gets ; push only while |
Scanning left to right, which loop gives each its nearest index to the left holding a value less than or equal to ?
- Pop while ; then the top, if any, is 's answer
- Pop while ; then the top, if any, is 's answer
- Pop while ; then the top, if any, is 's answer
- Pop while ; each popped index gets as its answer
Show the answer
B. Pop while ; then the top, if any, is 's answer
Popping every strictly larger value leaves on top the nearest earlier index whose value is at most ; equal values survive the pop, so they count. Popping is safe for later indices too: is closer to them and no larger, so it answers anything the popped indices could have.
Spans, waits, rain water and rectangles
Many classic problems are a nearest greater or smaller element in disguise:
- Stock span. For each day, how many consecutive days ending today had a price no higher than today's? It is minus the index of the previous strictly greater price. For prices the spans are .
- Waiting for a warmer day. The distance to the next greater temperature.
- The largest rectangle in a histogram. A rectangle as tall as bar can stretch left to just after the previous smaller bar and right to just before the next smaller one, so the answer is the maximum of over all bars.
Trapping rain water. Bars of heights hold water between them. The water above bar is the lower of two walls, the highest bar on its left and the highest bar on its right (counting bar itself on both sides), minus : with and for those two maxima, it is . A monotonic stack computes the same total layer by layer: when a taller bar arrives, each popped bar is the floor of a pool whose walls are the new top of the stack and the new bar.
def trapped_water(h):
water, stack = 0, [] # indices; heights never increase upward
for i, x in enumerate(h):
while stack and h[stack[-1]] < x:
bottom = stack.pop()
if not stack:
break # no wall on the left: the water spills
left = stack[-1]
width = i - left - 1
water += width * (min(h[left], x) - h[bottom])
stack.append(i)
return watertime and space. The two-pointer method needs only extra space: move inward from whichever side has the lower wall, since that wall bounds the water there.
Think first How many units of water do bars of heights trap?
The water level over each bar is : . Subtracting the heights gives units.
Sliding-window maximum: the monotonic deque
Now report the maximum of every window of consecutive elements (both ends inclusive). Recomputing each window costs ; a max-heap that lazily discards expired entries costs . A monotonic deque costs .
Keep the indices of the window's candidates in a deque, with values strictly decreasing from front to back. When arrives, every candidate at the back with a value is dominated: it is older and no larger, so it leaves the window first and can never again be the maximum. Pop those from the back and push . The front may have slid out of the window: pop it if its index is . The front is then the window's maximum.
from collections import deque
def window_max(a, k):
dq, out = deque(), [] # indices; values strictly decrease front to back
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x:
dq.pop() # dominated: older and not larger
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # the front left the window a[i-k+1 .. i]
if i >= k - 1:
out.append(a[dq[0]])
return outEach index enters the deque once and leaves at most once, from one end or the other, so the total time is , and the deque never holds more than indices. The window advances one position per step, so at most one index expires per step, and a single check of the front suffices.
Run window_max on with . Which values does the deque hold right after the last element is processed?
Show the answer
A.
When 5 arrives it dominates 2 and 3, which are popped from the back. Then 4 is pushed behind 5, because it is smaller and may become the maximum once 5 leaves. The front, 5, is the maximum of the last window, .
Recognizing it
Signals in a problem statement:
- "for each element, the nearest, next or previous greater or smaller one", "how far until …", "how many consecutive … before", "who can see whom" along a row of heights;
- "the maximum or minimum of every window of consecutive elements", or a dynamic program whose transition takes a minimum over a sliding range of earlier states;
- "the sum, over all subarrays, of their minimum or maximum": contribution counting with nearest smaller values;
- areas bounded by bar heights: rectangles under a histogram, water between walls;
- around to , which rules out the obvious scan (rule of thumb: about simple operations per second).
| Problem (in brief) | Structure | Key idea | Cost |
|---|---|---|---|
| Days until a warmer temperature | monotonic stack | next greater element, as a distance | |
| Stock span | monotonic stack | previous strictly greater element, as a distance | |
| Trapped rain water | monotonic stack, or two pointers | pop a floor; its walls are the new top and the new bar | |
| Largest rectangle in a histogram | monotonic stack | the previous and next smaller bars bound each bar's rectangle | |
| Maximum of every window of size | monotonic deque | drop dominated indices at the back and expired ones at the front | |
| Sum of the minimums of all subarrays | two monotonic stacks | contribution , strict on one side only |
Key takeaways
- A monotonic stack holds the indices still waiting for an answer; each index is pushed once and popped at most once, so every next or previous greater or smaller element takes in total.
- The comparison chooses the question: flip it for greater versus smaller, and use its strictness to decide how repeated values count, remembering that the two directions treat ties oppositely.
- Spans, waiting times, trapped water, histogram rectangles and sums of subarray minimums are nearest greater or smaller problems in disguise.
- A monotonic deque drops dominated candidates at the back and expired ones at the front, giving every sliding-window maximum or minimum in total time.
- Medians, -th largest values and arbitrary range queries do not fit: no candidate can be discarded, or the range does not slide.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What is the largest possible total number of pops in next_greater on an array of elements?
- , since step can pop up to indices
Show the answer
A.
Each index is popped at most once and the last index pushed is never popped, so there are at most pops; any increasing array reaches that. A single step can pop many indices, but only indices that earlier steps pushed and nobody popped.
You compute the sum of subarray minimums as , but with strictly smaller on both sides. What does that give on ?
- 6
- 12, the true sum
- 18
- 20
Show the answer
D. 20
With strict comparisons no index has a smaller neighbor, so and for all three, and the total is : subarrays with repeated minimums are counted once per copy. A non-strict comparison on one side counts each subarray exactly once and gives 12.
Which of these problems is not solved by a single monotonic stack or deque pass?
- For each day, the number of days until a warmer one
- The maximum of every window of 50 consecutive readings
- The median of every window of 50 consecutive readings
- The largest rectangle under a histogram
Show the answer
C. The median of every window of 50 consecutive readings
A monotonic structure keeps only the candidates that could still be the extreme value and discards dominated ones. A median depends on every element of the window, so nothing can be discarded; two heaps or an order-statistics tree give .
In window_max, with windows , when must the front index be removed?
- When
- When
- When
- When
Show the answer
B. When
The window starts at , so an index lies outside it. Only index leaves the window at step , and if it is still in the deque it is at the front, since every other index in the deque is larger.
Go deeper
- The Largest Rectangle & Maximal Submatrices · From histograms to the biggest all-ones rectangle in a binary matrix.
- Cartesian Trees & Nearest Smaller Values · The tree hidden in a monotonic stack, and its link to range minimum queries.
- Monotonic Queues in Dynamic Programming · Sliding-window optima that cut DP transitions from O(k) to O(1).
Further reading
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 8: nearest smaller elements and the sliding window minimum.
- CP-Algorithms, "Minimum stack / Minimum queue".
- O. Berkman, B. Schieber & U. Vishkin, "Optimal doubly logarithmic parallel algorithms based on finding all nearest smaller values," Journal of Algorithms 14(3) (1993), 344–370.