Learn the pattern · ~15 min
Monotonic Stack
also called next greater element, previous smaller element
Walk left to right and keep the days that are still waiting for an answer on a stack. Each new day answers every colder waiting day on top, then waits itself.
Reach for it when you read
- +For each element, the nearest bigger (or smaller) one to its right or left: next greater, previous smaller.
- +"How many days until…", "how far to the next taller…": a distance to the first element that beats this one.
- +"How many consecutive earlier days were ≤ today?" (a span): the first earlier element that beats today stops it.
- +Your brute force is a nested loop whose inner loop walks forward or back until it meets something bigger/smaller.
- +Build the smallest/largest number or string by deleting or keeping characters in order: keep a rising (or falling) run.
Not this one when
- ×The max or min of every window of size k: a monotonic deque, because old elements also expire from the front.
- ×The k largest overall, in any order: a heap. Position doesn't matter there.
- ×The closest element by value rather than by position: sort it, or a sorted set with binary search.
Learn Monotonic Stack
First, what does "monotonic" mean?
A sequence is monotonic increasing if it never goes down. 1, 2, 2, 4, 7 is monotonic increasing: it goes up or stays flat, but it never drops. If no two neighbours are equal, like 1, 2, 4, 7, we call it strictly increasing.
Flip it and you get monotonic decreasing: it never goes up. 9, 6, 6, 2 is one.
A monotonic stack is just a stack that stays sorted like this all the time. Push, pop, whatever you do, the values from bottom to top only rise (an increasing stack) or only fall (a decreasing stack).
How do we keep a stack increasing?
Take the array [3, 8, 5, 9, 2, 6] and walk it from left to right. The rule is one line:
Before you push the current number, pop every number on top that is bigger than or equal to it.
That way nothing on the stack is ever bigger than what's above it. Let's do it.
| i | number | what happens | stack (bottom → top) |
|---|---|---|---|
| 0 | 3 | stack is empty, push 3 | 3 |
| 1 | 8 | top is 3, smaller than 8, so push | 3, 8 |
| 2 | 5 | top is 8, bigger than 5: pop it. Now top is 3, smaller: push 5 | 3, 5 |
| 3 | 9 | top is 5, smaller: push | 3, 5, 9 |
| 4 | 2 | 9, 5 and 3 are all bigger than 2: pop all three, then push 2 | 2 |
| 5 | 6 | top is 2, smaller: push | 2, 6 |
Read the last column top to bottom: every row is rising. That's an increasing stack. Nothing magical, just "pop the bigger ones, then push".
The code for it
vector<int> st; // stores indices, not values
for (int i = 0; i < n; i++) {
while (!st.empty() && a[st.back()] >= a[i])
st.pop_back(); // a bigger one on top would break the order
st.push_back(i);
}You don't need to memorise this. It's exactly the table above: walk every element, pop while the top is bigger, push.
Why push the index and not the value? Because from an index you can always get the value (a[i]), but from a value you can't get back its position. Many problems need the position too: a distance, a width, "how many days until". So we always store indices.
Fine, but how does this help us?
Here's a classic problem: nearest smaller to the left. For every element, find the closest element on its left that is smaller than it. If there is none, write -1.
For [3, 8, 5, 9, 2, 6]:
| i | number | look left for the first smaller one | answer |
|---|---|---|---|
| 0 | 3 | nothing on the left | -1 |
| 1 | 8 | 3 is smaller | 3 |
| 2 | 5 | 8 is not smaller, 3 is | 3 |
| 3 | 9 | 5 is smaller | 5 |
| 4 | 2 | 9, 5, 8, 3: none is smaller than 2 | -1 |
| 5 | 6 | 2 is smaller | 2 |
So the answer is [-1, 3, 3, 5, -1, 2].
The brute force
The direct way is what we just did by hand. For each i, start a pointer j at i − 1 and walk left until a[j] < a[i].
vector<int> ans(n, -1);
for (int i = 0; i < n; i++)
for (int j = i - 1; j >= 0; j--)
if (a[j] < a[i]) { ans[i] = a[j]; break; }It's correct, but look at the worst case: when no element finds a smaller one quickly, j walks all the way back to 0 for every i. That's about n²/2 comparisons, O(n²). For n = 10⁵ that's roughly 5 × 10⁹ comparisons, and the judge gives you a second or two. Time limit exceeded.
The one thought that fixes it
Stop at index 2, the number 5. To its left sits an 8, which is bigger than 5.
Now think about any number that comes later, call it x:
- If 5 is smaller than
x, then 5 is a better answer than 8: it's smaller and closer. - If 5 is not smaller than
x, then 8 isn't either, because 8 is even bigger.
Either way, 8 can never be the answer for anyone after 5. It's useless from now on, so throw it away the moment 5 arrives.
And that's exactly what our increasing stack was doing: when a number arrives, it pops every bigger number before it, because those can never be an answer again. What's left on the stack are only the useful candidates, and the nearest one sits on top.
So after popping, the top of the stack is the answer. If the stack is empty, the answer is -1.
vector<int> ans(n, -1), st;
for (int i = 0; i < n; i++) {
while (!st.empty() && a[st.back()] >= a[i])
st.pop_back(); // bigger ones can never be an answer again
if (!st.empty())
ans[i] = a[st.back()]; // the top is the nearest smaller one
st.push_back(i);
}Dry run
Same array, [3, 8, 5, 9, 2, 6]. Watch the top of the stack at each step.
| i | number | popped | top after popping → answer | stack after push |
|---|---|---|---|---|
| 0 | 3 | none | empty → -1 | 3 |
| 1 | 8 | none | 3 → 3 | 3, 8 |
| 2 | 5 | 8 | 3 → 3 | 3, 5 |
| 3 | 9 | none | 5 → 5 | 3, 5, 9 |
| 4 | 2 | 9, 5, 3 | empty → -1 | 2 |
| 5 | 6 | none | 2 → 2 | 2, 6 |
[-1, 3, 3, 5, -1, 2], the same answer as the brute force.
Why it's O(n)
There's a while inside a for, so it looks like O(n²). Don't count loops, count what happens to each element: it is pushed exactly once, and popped at most once. So across the whole run there are at most n pushes and n pops, about 2n operations. That's O(n) time. The stack can hold up to n indices, so O(n) space.
From O(n²) down to O(n), just by throwing away elements that can never be the answer.
Nearest smaller to the right? Flip the loop
Want the nearest smaller element on the right instead? Change nothing except the direction: run the loop from i = n − 1 down to 0.
for (int i = n - 1; i >= 0; i--) { /* same body */ }For [3, 8, 5, 9, 2, 6] that gives [2, 5, 2, 2, -1, -1]. For example, to the right of 8 the first smaller number is 5.
Greater instead of smaller? A decreasing stack
Now the question is nearest greater element. Flip the comparison: pop while the top is smaller than or equal to the current number. The stack now falls from bottom to top, so it's a monotonic decreasing stack.
while (!st.empty() && a[st.back()] <= a[i])
st.pop_back(); // smaller ones can never be a "greater" answer againEverything else stays the same. On [3, 8, 5, 9, 2, 6]:
| i | number | popped | answer (nearest greater to the left) | stack after push |
|---|---|---|---|---|
| 0 | 3 | none | -1 | 3 |
| 1 | 8 | 3 | -1 | 8 |
| 2 | 5 | none | 8 | 8, 5 |
| 3 | 9 | 5, 8 | -1 | 9 |
| 4 | 2 | none | 9 | 9, 2 |
| 5 | 6 | 2 | 9 | 9, 6 |
Nearest greater to the left is [-1, -1, 8, -1, 9, 9]. Run the same loop right to left and you get nearest greater to the right: [8, 9, 9, -1, 6, -1].
Remember this
- Smaller → monotonic increasing stack. Greater → monotonic decreasing stack.
- Left → loop left to right. Right → loop right to left.
- Equal values: popping on
>=(or<=) gives you a strictly smaller (or greater) answer. If the problem counts equal values as an answer, pop on>(or<) instead. - Whenever a problem, however it's dressed up, asks "for every element, the first bigger or smaller one on one side", it's a monotonic stack question.
Practise it on Next Greater Element I, then Daily Temperatures (next greater to the right, but as a distance), Next Greater Element II (a circular array), Online Stock Span, Largest Rectangle in Histogram and Trapping Rain Water.
Below, watch Daily Temperatures run line by line.
Watch it work, line by line
Daily Temperatures ↗, t = [73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
Break it
Each card changes one line of the template the way it usually goes wrong in an interview. Before you open it, guess what the broken version prints.
< → <= in the pop condition
on [70, 70, 71]
What goes wrong?
< → <= in the pop conditionbroken → [1, 1, 0]
correct → [2, 1, 0]
An equal day is not warmer. With <=, day 1 (70) pops day 0 (70) and calls itself day 0's warmer day.
while → if: pop at most one day
on [73, 74, 75, 71, 69, 72, 76, 73]
What goes wrong?
while → if: pop at most one daybroken → [1, 1, 0, 0, 1, 1, 0, 0]
correct → [1, 1, 4, 2, 1, 1, 0, 0]
Day 5 (72) should answer both 69 and 71, and day 6 (76) both 72 and 75. With if, each day answers only one, so days 2 and 3 never get theirs.
Push today before the while instead of after it
on [73, 74, 75, 71, 69, 72, 76, 73]
What goes wrong?
while instead of after itbroken → [0, 0, 0, 0, 0, 0, 0, 0]
correct → [1, 1, 4, 2, 1, 1, 0, 0]
Now today is the top of the stack when the while checks it, and a day is never colder than itself. Nothing is ever popped.
ans[j] = i - j → ans[j] = i
on [73, 74, 75, 71, 69, 72, 76, 73]
What goes wrong?
ans[j] = i - j → ans[j] = ibroken → [1, 2, 6, 5, 5, 6, 0, 0]
correct → [1, 1, 4, 2, 1, 1, 0, 0]
That writes which day is warmer, not how many days away it is. Read the question: it asks for the wait.
When to use it, and when not
Ask yourself
For every element, am I looking for the first element on one side that is bigger (or smaller) than it?
Reach for it when
- +next/previous greater or smaller
- +span/temperature/visible buildings
- +largest rectangle in histogram
- +sum over subarrays of min/max
- +n up to 1e5-1e6
It fails 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
Looks like it, isn't (and the other way round)
- Sum of Subarray Minimums looks like Sliding Window, needs this pattern
No window condition; each element's contribution span comes from previous/next smaller.
- 132 Pattern looks like Two Pointers, needs this pattern
Need the best middle candidate for each position; a decreasing stack scanned from the right tracks it.
- Remove K Digits looks like Greedy, needs this pattern
The greedy 'drop a digit larger than the next' is implemented by a monotonic stack.
- Count of Smaller Numbers After Self looks like Monotonic Stack, needs Segment Tree / Fenwick (BIT)
Counts of all smaller elements, not the nearest one: BIT over compressed values or merge-sort counting.
Why this pattern and not another
You need each element's nearest greater/smaller (unbounded lookback) or to compute spans/areas — resolved in O(1) amortised by a stack that stays monotonic.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What does the stack hold, and in what order?Reveal
The indices whose answer is still unknown. Their values are monotone: falling from bottom to top when you look for the next greater.
2Why is it O(n) when there's a loop inside a loop?Reveal
Every index is pushed once and popped at most once, so the inner
whileruns at most n times in total.3Next greater versus previous greater: where is the answer written?Reveal
Next: when an element is popped, by the one doing the popping. Previous: read from the top of the stack after popping, before you push.
Practice ladder
- 1Next Greater Element Ithe base ideaEasy
- 2Daily Temperaturesthe hookMedium
- 3Next Greater Element IIcircular arrayMedium
- 4Online Stock Spanlook backMedium
- 5Remove K Digitsthe stack is the answerMedium
- 6Sum of Subarray Minimumscontribution countingMedium
- 7Trapping Rain Waterwater in the dipsHard
- 8Largest Rectangle in Histograma rectangle on every popHard
Finished Monotonic Stack? Mark it done and Lessgo moves you to the next step.