For every bar in a row, which is the next taller one to its right? The brute-force answer looks right at every pair — O(n²). The elegant answer keeps a single stack that only ever decreases, so the moment a taller bar arrives it resolves everything shorter waiting below it. One pass, and a whole family of problems falls.
O(n) time · O(n) space · stack · arrays
next greater
For each element, the first element to its right that is strictly larger — or none.
monotonic
A stack kept in sorted order. Here: values decrease from bottom to top.
the pop
A new taller bar pops every shorter bar off the stack — each just found its answer.
amortized O(n)
Each bar is pushed once and popped once, so total work is linear despite the inner loop.
next_greater.js — a stack that only decreases
Ready
A row of bars. We want each bar's next greater element — the first taller bar to its right. Press Step to walk the pointer, keeping a stack of bars still waiting for their answer.
–
pointer i
0
stack size
0
resolved
0
push+pop ops
How it works
The insight is that a bar can’t know its next-greater neighbor until that neighbor appears. So we keep every bar still waiting for an answer on a stack — and because any bar taller than one already waiting would have resolved it, the waiting bars are always in decreasing order. That invariant is the whole trick.
1
Scan left to right
Move a pointer i across the array. The current bar is the candidate answer for everything shorter still waiting.
2
Pop everything shorter
While the stack’s top bar is shorter than arr[i], pop it — its next greater element is arr[i]. Record the answer.
3
Push the current bar
Now arr[i] joins the stack to wait for its next greater element. The stack stays decreasing.
4
Whatever’s left has no answer
Bars still on the stack at the end never found a taller neighbor — their next greater element is “none”.
Time
O(n)
Space
O(n)
Each element
pushed 1×, popped ≤1×
Brute force
O(n²)
The code
# next greater element for every index, O(n)def next_greater(arr):
n = len(arr)
ans = [-1] * n
stack = [] # indices, values decreasingfor i in range(n):
while stack and arr[stack[-1]] < arr[i]:
ans[stack.pop()] = arr[i] # resolved!
stack.append(i)
return ans # leftovers stay -1
Store indices, not values, so you can also compute distances (as in "daily temperatures": how many days until a warmer one). Flip the comparison to > for next-smaller; scan right-to-left for previous greater/smaller. Four problems, one skeleton.
Quick check
1. Why is the stack always in decreasing order?
Exactly — a new bar pops everything shorter before pushing, so only strictly-taller-downward bars remain. The invariant maintains itself.
2. There’s a while-loop inside the for-loop. Why is it still O(n)?
Amortized analysis: the inner loop can pop many at once, but no element is popped twice, so the total pop count over all iterations is bounded by n.
FAQ
What is a monotonic stack?
A stack kept in sorted order — always increasing or always decreasing — by popping elements that would break the order before pushing a new one. It turns "nearest larger/smaller neighbor" questions into a single linear pass.
Why store indices instead of values?
Indices let you recover both the value (arr[idx]) and the distance (i - idx). Problems like "daily temperatures" need the distance, so indices are the more general choice.
What problems use a monotonic stack?
Next/previous greater or smaller element, daily temperatures, largest rectangle in a histogram, trapping rain water, stock span, and remove-K-digits. Any "nearest bigger/smaller" pattern is a candidate.
Increasing or decreasing stack — which do I use?
For next-greater you keep values decreasing (pop when a bigger one arrives). For next-smaller, keep them increasing. Pick the order so the element that "resolves" a waiting item is the one that breaks the invariant.
The picture: every bar points at its first taller neighbour
The page’s array [3, 7, 1, 5, 4, 8, 2, 6]. Each arc runs from a bar to the first strictly larger bar on its right; the numbers beneath are the answers. The 8 and the final 6 never find a taller neighbour, so they stay −1. Note that arcs nest but never cross: that is the stack discipline.
Worked example, step by step
Run next_greater on [3, 7, 1, 5, 4, 8, 2, 6]. The stack holds indices of bars still waiting; the column shows their values, bottom first. Before pushing bar i, pop every waiting bar smaller than it.
i
arr[i]
Pops (answer found)
Stack after push (values)
Size
0
3
none
[3]
1
1
7
idx 0 (3) → 7
[7]
1
2
1
none
[7, 1]
2
3
5
idx 2 (1) → 5
[7, 5]
2
4
4
none
[7, 5, 4]
3
5
8
idx 4 (4), idx 3 (5), idx 1 (7) → 8
[8]
1
6
2
none
[8, 2]
2
7
6
idx 6 (2) → 6
[8, 6]
2
Row 5 is the payoff: the 8 pops 4, 5 and 7 in one go, giving all three the answer 8, and it empties the stack down to itself. Rows 0, 2, 4 and 6 pop nothing because each new bar is smaller than the one before it, so the stack just grows. The stack is decreasing from bottom to top after every row: [7], [7, 1], [7, 5, 4], then [8, 2]. In total there were 8 pushes and 6 pops, and the 2 bars left at the end (the 8 and the 6) keep their −1. The answer array is [7, 8, 5, 8, 8, −1, 6, −1]. An inner while loop did not make this quadratic: 6 pops plus 2 leftovers equals the 8 pushes.
Complexity and trade-offs
Case
Time
Space
Why
Monotonic stack
O(n)
O(n)
Each index is pushed once and popped at most once, so total work is at most 2n.
Brute force scan right
O(n²)
O(1)
For each bar, walk right until something larger. A descending array makes every walk go to the end.
Sort plus binary search
O(n log n)
O(n)
Awkward: you need the first larger value by position, not by rank.
Segment tree descent
O(n log n)
O(n)
Works for “first element greater than x in a range” with updates, which the stack cannot handle.
Monotonic deque (windows)
O(n)
O(k)
Same invariant plus evicting from the front; used when the neighbour must lie within a window.
The stack is optimal because you must read every element. Its limit is that it answers a question about the whole array at once, offline. If bars change between queries, or if each query restricts the range, you need a tree. Its space is O(n) only in the worst case: a strictly decreasing array leaves every index on the stack at the end.
Common mistakes
Using ≤ when the problem says strictly greater
Popping while arr[top] ≤ arr[i] answers “next greater or equal”. On [2, 2] the first 2 would wrongly resolve to 2. Use < for strictly greater.
Storing values when you need distance
“Daily temperatures” asks how many days until warmer. With values on the stack you know the temperature but not the index, so you cannot compute i − idx. Store indices and read values through the array.
Scanning the wrong direction for “previous”
The left-to-right pass gives the next greater element. For the previous greater, either scan right to left or read the stack top before pushing: on the first pass the element under the new bar is its previous greater.
Treating the leftovers as an error
Bars still on the stack at the end have no answer. Initialising the answer array to −1 (or n for distance problems) handles them; popping them with a made-up sentinel is the usual alternative.
Circular arrays scanned once
For a circular array, one pass leaves bars unresolved that would find a larger value by wrapping. Iterate i from 0 to 2n − 1 using i % n, and push only during the first n.
Where this shows up
Largest rectangle in a histogram
LeetCode 84 asks for the biggest rectangle under a histogram. Each bar’s rectangle extends to the nearest smaller bar on each side, so two monotonic-stack passes (or one, with a clever pop) give all widths in O(n).
Daily temperatures and next greater element
LeetCode 739 (days until a warmer day) and 496 / 503 (next greater element, including the circular form) are the problem in its pure form.
Trapping rain water
LeetCode 42 has a stack solution: pop a bar when a taller one arrives and add the water bounded by the new bar and the one now on top.
Stock span
The classic “span of stock’s price” question asks, for each day, how many consecutive earlier days had price at most today’s. That is previous greater with a pop-while-smaller-or-equal rule.
SOLVE IT YOURSELF
Solve it: next greater element
The brute force is two nested loops and O(n²). One stack turns it into a single pass. Write it in Python or TypeScript, running for real in your browser. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests.
YOUR TASK
Implement next_greater(nums): for each element, return the first strictly greater element to its right, or -1 if there is none. So [2, 1, 2, 4, 3] gives [4, 2, 4, -1, -1].
HINTS — 5 IDEAS
Keep a stack of indices whose answer you have not found yet, not of values.
For each new value v: while the stack top holds a smaller value, v is its answer — pop it and record.
Then push the current index. The stack stays non-increasing by value — that is the "monotonic" part.
Anything still on the stack at the end never found a greater element, so it keeps -1.
Each index is pushed once and popped at most once, so the whole thing is O(n) despite the inner while loop.