Monotonic Stack
O(n)
Keep the stack increasing/decreasing; when the new element breaks the order, pop — each pop is an answer.
0/34 solved
Recognise it
The signal
Next/previous greater or smaller for every index, histogram rectangles, trapping rain water, spans, sum of subarray mins/maxes.
1Brute force
For each element scan right/left until a bigger one: O(n2).
2The observation
Rescanning: an element that is dominated can never be anyone's answer, so it is popped once.
3Why it works
The stack holds the indices still waiting for their answer, in monotone order; each is pushed and popped once.
Reach for it when
- +Next/previous greater or smaller element for every position.
- +Histogram / rectangle areas, trapping rain water, span problems (how far back/forward a condition holds).
- +You feel an O(n²) 'for each element scan onward' that resolves to amortized O(n).
Not when
- ×Max/min over a fixed-size sliding window (must evict from the front)use Monotonic deque
- ×Arbitrary range-min queriesuse Sparse table
- ×Order doesn't matter, you need global counts/extremes (a heap gives global, not nearest)use Heap or simple scan
- ×The relation isn't 'nearest element that breaks monotonicity'use Something else; a stack won't help
Intuition
A monotonic stack keeps its contents always sorted (always increasing, or always decreasing). It's the go-to for "next/previous greater/smaller element" and anything where each element is waiting for the first later element that beats it.
Read the full intuition
The idea with a tiny story: people queue holding numbered tickets, and you want each person to know the next taller person behind them. Keep a stack of "people still waiting for someone taller." A new taller person arrives → they're the answer for everyone shorter still waiting, so pop those off and resolve them; then the newcomer waits too. Each person is pushed once and popped once → O(n) even though it feels nested.
Skeleton ("next greater to the right", store indices):
for i in range(n):
while stack and a[stack[-1]] < a[i]: # a[i] beats the waiting one
j = stack.pop(); ans[j] = a[i] # resolve j
stack.append(i) # i now waitsThe direction of the comparison sets everything:
<(pop smaller) → strictly increasing stack → finds next greater.>(pop larger) → decreasing stack → finds next smaller.- Iterate left→right for next, right→left for previous.
Key idea
Store indices, not values — you usually need the distance (Daily Temperatures) or to compute a width (Histogram). The value is always one lookup away as
a[stack[-1]].
Why it costs what it costs
Time O(n). each index is pushed once and popped at most once, so total stack operations are ≤ 2n despite the inner while.
Space O(n). the stack can hold up to all n indices (a fully monotonic input).
Practice
- Nearest Smaller ValuesFoundationFoundationCSESMedium
- Daily TemperaturesApply it · Next greater distance.Apply itAmazon, MetaMedium
- Next Greater Element IIOne change · Circular array.One changeAmazon, UberMedium
- Online Stock SpanOne change · Streaming.One changeAmazon, CitadelMedium
- 132 PatternTwists · Need the middle value of a triple.TwistsCitadel, AmazonMedium
- Remove K DigitsBranches · Greedy deletion via stack.BranchesAmazon, MicrosoftMedium
- Largest Rectangle in HistogramBranches · Need both previous and next smaller.BranchesAmazon, GoogleHard
- Maximal RectangleCombine · 2D matrix.CombineGoogle, AmazonHard
- Sum of Subarray MinimumsAdvanced · Sum over all subarrays.AdvancedCitadel, Goldman SachsMedium
- Sum of Subarray RangesMastery checkMastery checkMedium
- Next Greater Element IAmazon, AdobeEasy
- Trapping Rain WaterAmazon, GoogleHard
Pitfalls
Classic bugs
- !Storing values instead of indices — you can't compute distances or widths.
- !
<vs<=decides how equal values are handled; pick deliberately or contribution sums double-count. - !Leftovers on the stack at the end have no next-greater — keep their default.
- !Circular array: loop
2ntimes withi % n; only push indices during the first pass. - !Histogram width on pop is
i - stack[-1] - 1; sentinel 0 heights at both ends simplify it.
Looks like it, isn't
- Count of Smaller Numbers After Self needs Segment Tree / Fenwick (BIT)
Why
Counts of all smaller elements, not the nearest one: BIT over compressed values or merge-sort counting.
Go deepervariants and techniques · 5 combinations · interviewer follow-ups · resources
Variants and techniques
- Stack for Matching & Expression ParsingUse a plain LIFO stack to match nested structures (brackets, tags, decode strings) and evaluate expressions with precedence.
- Contribution Technique (sum over all subarrays/pairs)Instead of enumerating all subarrays/pairs, compute how many of them each element contributes to and sum value x count.
- Next/previous greater or smallerFlip the comparison and the iteration direction. Next Greater Element I/II, Daily Temperatures (distance).
- SpansPop while the condition holds, span = i - newTop. Online Stock Span.
- Histogram / rectangleIncreasing stack; on pop, area = height·width using bracketing indices. Largest Rectangle in Histogram, Maximal Rectangle.
- Trapping waterDecreasing stack of bars; on a taller bar, pop and add trapped water bounded by the new neighbours. Trapping Rain Water (stack variant).
Combinations
Monotonic Stack+Contribution Technique (sum over all subarrays/pairs)
sum over all subarrays of min, max, or range
- Monotonic Stack:
- finds each element's span where it is min/max
- Contribution Technique (sum over all subarrays/pairs):
- sums value x number of subarrays
Monotonic Stack+Grid / Matrix DP
largest all-ones rectangle in a binary matrix
- Monotonic Stack:
- largest rectangle in each histogram
- Grid / Matrix DP:
- builds column heights row by row
Probability & Expected-Value DP (linearity of expectation)+Contribution Technique (sum over all subarrays/pairs)
expected number of inversions / empty squares / matches
- Probability & Expected-Value DP (linearity of expectation):
- linearity: sum the indicator probabilities
- Contribution Technique (sum over all subarrays/pairs):
- split the total into per-pair or per-square indicators
Monotonic Stack+Contribution Technique (sum over all subarrays/pairs)+Prefix Sum
sum over all subarrays of min * sum (or similar products)
- Monotonic Stack:
- previous/next smaller bounds for each element
- Contribution Technique (sum over all subarrays/pairs):
- each element is the min of all subarrays inside its bounds
- Prefix Sum:
- prefix sums of prefix sums give those subarrays' total sum in O(1)
Binary Lifting & LCA+Monotonic Stack
count elements of the 'next greater' chain starting at a that lie within b
- Binary Lifting & LCA:
- count how many next-greater jumps stay within [a, b]
- Monotonic Stack:
- next greater element for every index
Follow-ups interviewers ask
- 01Next smaller instead of greater? → flip the pop comparison (pop while top is larger).
- 02Previous greater/smaller? → iterate right-to-left, same machinery.
- 03Circular array (wrap-around)? → iterate 2n times with
i % n. - 04Histogram area / trapping water? → store indices and compute width = i − newTop − 1 on each pop; sentinels flush the stack.
State table
| i | a[i] | pop while a[top]<a[i] | stack (idx) | resolved |
|---|---|---|---|---|
| 0 | 2 | — | [0] |
— |
| 1 | 1 | — | [0,1] |
— |
| 2 | 2 | pop 1 (a=1<2) | [0,2] |
NGE[1]=2 |
| 3 | 4 | pop 2,0 | [3] |
NGE[2]=4, NGE[0]=4 |
| 4 | 3 | — | [3,4] |
— |