Quick reference
A monotonic stack is a stack whose items are always in sorted order, either increasing or decreasing from bottom to top. Before you push a new item, you pop every item that would break the order, and each pop answers a question about the item you popped, like "what's the next bigger number to my right?" That turns problems such as next greater element and daily temperatures from O(n²) into O(n).
When to use it:
- For each item in an array, you need the nearest item to its left or right that's bigger or smaller: the next greater element, the previous smaller element, the number of days until a warmer day.
- You need to know how far each item can stretch before something bigger or smaller blocks it, as in largest rectangle in a histogram or stock span.
Two kinds:
- Decreasing (values get smaller from bottom to top): finds the next or previous greater item.
- Increasing (values get bigger from bottom to top): finds the next or previous smaller item.
Cost:
- O(n) time, because each index is pushed once and popped at most once. O(n) space for the stack in the worst case.
When to Use a Monotonic Stack
Reach for a monotonic stack when a problem about an array has these signals:
-
It asks for something for every item: "for
each day," "for each bar," "return
an array where
answer[i]is ..." - That something is the nearest bigger or smaller item, or how far away it is: "next greater," "next warmer day," "previous smaller," "how many days in a row was the price at most today's," "how wide can this bar's rectangle get."
- The brute-force solution scans left or right from every item until it finds the answer, which is O(n²).
The stack holds the items that are still waiting for their answer. When a new item arrives, it settles the question for every waiting item it beats, and those come off the stack. It stops at the first item it doesn't beat and lands on top of it, so the stack always stays in sorted order. That's where the name comes from: "monotonic" means always moving in one direction.
How a Monotonic Stack Works: Next Greater Element
Example problem: for each number, find the first number to its right that's bigger. If there isn't one, use −1.
Take [3, 1, 4, 1, 5, 2]. The answer is [4, 4, 5, 5, −1, −1]: the first bigger number after the 3 is 4, after the first 1 it's also 4, and so on. Nothing to the right of the 5 or the last 2 is bigger.
We walk left to right. The stack holds the indexes of numbers that haven't found a bigger number yet. Before pushing each new index, we pop every index whose number is smaller than the new one, because the new number is the answer for all of them:
| Index | Number | Pops (answer found) | Stack after (indexes) | Their numbers |
|---|---|---|---|---|
| 0 | 3 | Nothing (the stack is empty) | [0] | [3] |
| 1 | 1 | Nothing: 3 isn't smaller than 1 | [0, 1] | [3, 1] |
| 2 | 4 | Index 1 (the 1): answer 4. Index 0 (the 3): answer 4. | [2] | [4] |
| 3 | 1 | Nothing: 4 isn't smaller than 1 | [2, 3] | [4, 1] |
| 4 | 5 | Index 3 (the 1): answer 5. Index 2 (the 4): answer 5. | [4] | [5] |
| 5 | 2 | Nothing: 5 isn't smaller than 2 | [4, 5] | [5, 2] |
| End | Indexes 4 and 5 never got popped, so their answer stays −1 |
Look at the "Their numbers" column: it always gets smaller from bottom to top. This is a decreasing monotonic stack. It has to be: if a smaller number sat below a bigger one, the bigger one would have popped it on the way in.
Why is each popped number's answer right? When index 0 (the 3) gets popped by the 4, nothing between them was bigger than 3, or it would have popped the 3 first. So the 4 really is the first bigger number to the right of the 3.
Store indexes, not values
Notice that the stack holds indexes, and we look up the number with
nums[index] when we need it. That's the usual way to
write a monotonic stack, for three reasons:
- When we pop an item, we need to know where to write its answer.
- Many problems want a distance, like "how many days until it's warmer" or "how wide is this rectangle," and that's a difference of two indexes.
- Values can repeat. The input above has two 1s, and with values alone you couldn't tell which one you just popped.
Increasing vs. Decreasing Monotonic Stack
Which order you keep depends on the question. Here's the cheat sheet, for a left-to-right pass. "Decreasing" means the values get smaller from the bottom of the stack to the top:
| For each item, find the ... | Keep the stack | Pop while the top's value is | Where the answer comes from |
|---|---|---|---|
| Next greater item (to the right) | Decreasing | Smaller than the new item | Each popped item's answer is the new item |
| Next smaller item | Increasing | Bigger than the new item | Each popped item's answer is the new item |
| Previous greater item (to the left) | Decreasing | Smaller than or equal to the new item | The new item's answer is whatever is on top after popping (none if the stack is empty) |
| Previous smaller item | Increasing | Bigger than or equal to the new item | The new item's answer is whatever is on top after popping (none if the stack is empty) |
An easy way to remember it: the stack holds items that are waiting for a greater item, so the greater item has to be able to knock them off. That means smaller items sit on top of bigger ones, which is a decreasing stack. Waiting for a smaller item flips everything.
There are two places to read an answer, and one pass gives you both:
- When an item is popped, the item doing the popping is its next greater (or smaller) item.
- After the popping stops, the item left on top is the new item's previous greater (or smaller) item, since everything between them got popped.
Example: stock span (previous greater)
The span of a stock's price on a given day is how many days in a row, ending today, the price was at most today's price. For prices [100, 80, 60, 70, 60, 75, 85], the spans are [1, 1, 1, 2, 1, 4, 6]. On the day the price is 75, the four days 60, 70, 60, 75 were all at most 75, and the 80 before them stops the run.
That run ends right after the previous greater price. So keep a decreasing stack of days, pop every day whose price is at most today's, and the day left on top is the previous greater price. The span is today's index minus that day's index, or today's index + 1 if the stack is empty:
| Day | Price | Popped (prices at most today's) | Previous greater (day: price) | Span |
|---|---|---|---|---|
| 0 | 100 | – | none | 0 + 1 = 1 |
| 1 | 80 | – | 0: 100 | 1 − 0 = 1 |
| 2 | 60 | – | 1: 80 | 2 − 1 = 1 |
| 3 | 70 | day 2 (60) | 1: 80 | 3 − 1 = 2 |
| 4 | 60 | – | 3: 70 | 4 − 3 = 1 |
| 5 | 75 | day 4 (60), day 3 (70) | 1: 80 | 5 − 1 = 4 |
| 6 | 85 | day 5 (75), day 1 (80) | 0: 100 | 6 − 0 = 6 |
Popping prices that are equal to today's is what makes them count toward the span. For "next greater," you'd pop only strictly smaller items instead, so an equal item doesn't count as greater. Getting this comparison right matters whenever the input can have repeats.
Daily Temperatures: Days Until a Warmer Day
Example problem: given daily temperatures, return how many days you'd wait after each day for a warmer one, or 0 if no warmer day comes.
This is next greater element, but the answer is a distance instead of a value, which is why we store indexes. For [70, 68, 72, 71, 69, 75], the answer is [2, 1, 3, 2, 1, 0]:
| Day | Temperature | Pops (wait = today − that day) | Stack after (days) |
|---|---|---|---|
| 0 | 70 | – | [0] |
| 1 | 68 | – | [0, 1] |
| 2 | 72 | day 1: 2 − 1 = 1, day 0: 2 − 0 = 2 | [2] |
| 3 | 71 | – | [2, 3] |
| 4 | 69 | – | [2, 3, 4] |
| 5 | 75 | day 4: 1, day 3: 2, day 2: 3 | [5] |
Day 5 is still on the stack at the end, so its wait stays 0.
Largest Rectangle in a Histogram
Example problem: a histogram has bars of width 1 and the given heights, side by side. Find the area of the largest rectangle that fits inside it.
This is the hard classic, and it's worth understanding fully. The key idea: the biggest rectangle is as tall as some bar. If we use bar b's full height, the rectangle can stretch left and right until it hits a bar that's shorter. So for each bar, we need:
- The previous smaller bar (the left wall), and
- The next smaller bar (the right wall).
The rectangle's width is everything strictly between the walls:
right - left - 1. An increasing stack
finds both walls at the moment a bar is popped: the bar doing the
popping is the right wall, and the bar under it on the stack is the
left wall. If the stack is empty after the pop, there's no shorter
bar to the left, and we use −1 as the left wall.
One more trick: bars still on the stack at the end never found a right wall. We add a pretend bar of height 0 after the last bar, which pops everything, so every bar gets measured.
Here it is on heights [2, 4, 3, 5, 1]:
| Index | Height | Pops: bar (height), width = index − left wall − 1, area | Stack after (indexes) | Best |
|---|---|---|---|---|
| 0 | 2 | – | [0] | 0 |
| 1 | 4 | – | [0, 1] | 0 |
| 2 | 3 | bar 1 (4): left wall 0, width 2 − 0 − 1 = 1, area 4 | [0, 2] | 4 |
| 3 | 5 | – | [0, 2, 3] | 4 |
| 4 | 1 |
bar 3 (5): left wall 2, width 4 − 2 − 1 = 1, area 5 bar 2 (3): left wall 0, width 4 − 0 − 1 = 3, area 9 bar 0 (2): no left wall (−1), width 4 − (−1) − 1 = 4, area 8 |
[4] | 9 |
| 5 (pretend bar) | 0 | bar 4 (1): no left wall (−1), width 5 − (−1) − 1 = 5, area 5 | [5] | 9 |
The answer is 9: height 3 across indexes 1 to 3 (the bars 4, 3, and 5). Bar 2 couldn't stretch left past bar 0 (height 2) or right past bar 4 (height 1), and those are exactly the two walls it saw when it was popped.
What about bars with equal heights? The code pops while the top is at least as tall as the new bar, so the earlier of two equal bars gets popped by the later one and measured with a width that's too short. That's fine: the later bar has the same height, and when it's popped, its left wall is the earlier bar's left wall, so it gets the full width.
Checking every bar by stretching left and right takes O(n²) time. The stack version takes O(n) time and O(n) space.
Trapping Rain Water with a Monotonic Stack
Example problem: bars of the given heights stand side by side. After it rains, how many units of water sit between them?
Keep a decreasing stack of bar indexes. When a taller bar arrives, it pops a shorter bar, which becomes the floor of a pool. The bar now on top of the stack is the pool's left wall and the new bar is its right wall. The water over that floor is one layer:
-
Width:
i - left - 1, the bars strictly between the walls. -
Depth:
min(heights[left], heights[i]) - floor, since water spills over the shorter wall.
If nothing is left on the stack after the pop, there's no left wall and the water runs off. Here it is on [3, 0, 2, 0, 4]:
| Index | Height | Pops: floor, left wall, width × depth | Stack after | Water |
|---|---|---|---|---|
| 0 | 3 | – | [0] | 0 |
| 1 | 0 | – | [0, 1] | 0 |
| 2 | 2 | floor 0 (index 1), left wall index 0 (height 3): 1 × (min(3, 2) − 0) = 2 | [0, 2] | 2 |
| 3 | 0 | – | [0, 2, 3] | 2 |
| 4 | 4 |
floor 0 (index 3), left wall index 2 (height 2): 1 × (min(2, 4) − 0) = 2 floor 2 (index 2), left wall index 0 (height 3): 3 × (min(3, 4) − 2) = 3 floor 3 (index 0), no left wall: runs off |
[4] | 7 |
The stack fills the water in horizontal layers: first the two pools up to height 2, then one layer across indexes 1 to 3 from height 2 up to height 3. The total is 7.
This problem also has a two-pointer solution. The water over each bar is the shorter of the tallest bar to its left and the tallest bar to its right, minus the bar's own height. Start a pointer at each end, remember the tallest bar each one has passed, and always move the pointer on the side with the shorter tallest bar, since that side's water level is already settled. That fills the water one column at a time:
| Monotonic stack | Two pointers | |
|---|---|---|
| Fills the water | Layer by layer, as each pool gets closed off | Column by column |
| Time | O(n) | O(n) |
| Extra space | O(n) for the stack | O(1) |
In an interview, either one is a strong answer. Two pointers uses less space. The stack version is worth knowing because it's the same pattern as largest rectangle in a histogram, upside down.
Monotonic Stack Time and Space Complexity
A while loop inside a for loop looks like
O(n²), but a monotonic stack runs in
O(n) time. Count the work by item
instead of by loop: each index is pushed onto the stack
exactly once, and popped at most once. So across the whole
run there are at most n pushes and
n pops, and every pass through the
while loop does one of those pops. Some steps pop a lot
and some pop nothing, but the total is at most n,
which makes each step O(1)
amortized.
The stack takes O(n) space in the worst case. For next greater element, an array that only goes down, like [5, 4, 3, 2, 1], never pops anything, so every index is on the stack at the end.
| Problem | Brute force | Monotonic stack |
|---|---|---|
| Next greater element | O(n²): scan right from every item | O(n) time, O(n) space |
| Daily temperatures | O(n²) | O(n) time, O(n) space |
| Stock span | O(n²): scan left from every day | O(n) time, O(n) space |
| Largest rectangle in a histogram | O(n²): stretch left and right from every bar | O(n) time, O(n) space |
| Trapping rain water | O(n²): find the tallest bar on each side of every bar | O(n) time, O(n) space |
This "count the total moves, not the moves per step" argument is the same one that makes a sliding window O(n). For more on counting steps like this, see our big O notation guide.
Monotonic Stack vs. Monotonic Queue (Deque)
A monotonic queue is a close cousin. It's a double-ended queue (a deque) that pops from the back to keep its items in order, just like a monotonic stack, but it also removes items from the front when they get too old.
That's exactly what sliding window maximum needs: the largest number in every window of k numbers in a row. Keep a deque of indexes whose values decrease from front to back. Each new number pops the smaller numbers off the back (they can never be a window's maximum again), and the front index is dropped once it slides out of the window. The front is always the current window's maximum, and the whole pass takes O(n) time. See our sliding window guide for more on windows.
| Monotonic stack | Monotonic queue (deque) | |
|---|---|---|
| Removes items from | The top only | The back (to keep the order) and the front (when items leave the window) |
| Answers | The nearest greater or smaller item for every item | The maximum or minimum of a window that slides |
| Classic problem | Next greater element, daily temperatures | Sliding window maximum |
Common Monotonic Stack Mistakes
-
Storing values instead of indexes. You need the index to write the answer into the right slot and to measure distances and widths. You can always get the value back with
nums[index]. -
Using the wrong comparison when values repeat. For "next greater," pop only while the top is strictly smaller (
<). If you pop on equal values too, then in [2, 2, 3] the first 2 gets the second 2 as its "greater" item. For stock span, the opposite is right: pop equal prices too, so they count toward the span. -
Forgetting the items left at the end. They never found an answer. Fill the answer array with the default (−1 or 0) up front, or, for largest rectangle, add a pretend bar of height 0 at the end so every bar gets popped and measured.
-
Mixing up increasing and decreasing. Looking for something greater means a decreasing stack. If you're not sure, trace three or four items by hand and check which items your loop pops.
-
Searching the whole stack. The
whileloop should stop as soon as the top item stays. Everything under it is already in order, and looking past the top is what turns an O(n) solution into an O(n²) one. -
Confusing it with a max stack. A max stack (as in our Largest Stack question) keeps a second stack of the largest item so far, so it can report the stack's maximum in O(1) time. Its second stack is in sorted order too, but it never pops items to make room for a new one, so it's a different trick that answers a different question.
Classic Monotonic Stack Problems
-
Next greater element. Decreasing stack; each
popped item's answer is the item that popped it. For a
circular array, loop
through it twice (index
i % n), pushing only on the first time around. -
Daily temperatures. Next greater element, but
record
today - poppedDay. - Stock span. Previous greater price: pop every price at most today's, then the span reaches back to the day on top.
- Largest rectangle in a histogram. Increasing stack; measure each bar when it's popped. Maximal rectangle of 1s in a grid builds on it: treat each row as the bottom of a histogram, where each bar's height is the number of 1s in an unbroken run straight up from that row.
- Trapping rain water. Decreasing stack that fills a layer each time a pool is closed off, or two pointers with O(1) space.
- Sum of subarray minimums. Each item is the minimum of (i − previous smaller index) × (next smaller index − i) subarrays, and two monotonic stack passes find those indexes. To avoid counting ties twice, use a strict comparison on one side and a non-strict one on the other.
- Remove k digits to make the smallest number. Keep an increasing stack of digits, and pop a bigger digit whenever a smaller one arrives and you still have removals left.
- Sliding window maximum. The monotonic deque version, described above.
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake