“For each day, how many days until it gets warmer?” The obvious way checks every later day for every day: O(n²). The monotonic stack answers it in one pass, and the same trick solves next greater element, stock span and the famous histogram problem. It builds on the plain stack from Part 6.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
The concert line story
People stand in a line, all facing the stage. Each person wants to know: who is the first taller person in front of me? Short people wait. When a tall person shows up, every shorter person waiting behind them gets their answer at once and stops waiting. The people still waiting always stand in falling order of height: that's the “monotonic” part.
🌡️ How many days until a warmer day?
Stack: days still waiting
Answer: days to wait
Day 1 is 73°: not warmer than anyone waiting. It joins the stack and waits too.
The stack always holds days with falling temperatures (that's the “monotonic” part). Each day is pushed once and popped at most once, so the whole walk is O(n), not O(n²).
🔍 Use a monotonic stack when you see
- ✓“Next greater / smaller element” for every item
- ✓“How many days until warmer / a higher price?”
- ✓“First taller to the left or right”
- ✓Histogram rectangles, trapping rain water
🚫 Don't use it when
- ✗You need the K biggest overall (use a heap)
- ✗Matching brackets (a plain stack is enough)
- ✗A contiguous window with a rule (sliding window)
The template
answer = [-1] * n
stack = [] # indexes still waiting
for i in range(n):
while stack and nums[stack[-1]] < nums[i]:
answer[stack.pop()] = nums[i] # they found a bigger one
stack.append(i)
# whoever is left never found one (-1)⚡ Memory tricks
- 1
“Waiting room”
The stack is a waiting room of items that haven't found their answer yet.
- 2
“Bigger walks in, smaller walk out”
A bigger arrival pops every smaller one waiting: they're answered.
- 3
“Store the index, not the value”
Indexes give you both the value and the distance.
- 4
“In once, out once: O(n)”
Nobody is pushed or popped twice.
Code: next greater element and daily temperatures
Outputs in the comments come from running the code.
def next_greater(nums):
"""For each number, the first bigger number to its right (-1 if none)."""
answer = [-1] * len(nums)
stack = [] # indexes still waiting for a bigger number
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
answer[stack.pop()] = x # x is the bigger number they were waiting for
stack.append(i)
return answer
def daily_temperatures(temps):
"""How many days until a warmer day? (0 if never)"""
wait = [0] * len(temps)
stack = [] # days still waiting for a warmer day
for day, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
cold_day = stack.pop()
wait[cold_day] = day - cold_day
stack.append(day)
return wait
print(next_greater([2, 1, 2, 4, 3])) # [4, 2, 4, -1, -1]
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73])) # [1, 1, 4, 2, 1, 1, 0, 0]One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Next Greater Element I | Decreasing stack, pop when bigger arrives | Easy |
| Daily Temperatures | Store days, answer = day − cold day | Medium |
| Online Stock Span | Pop smaller-or-equal prices, add their spans | Medium |
| Next Greater Element II (circular) | Loop the array twice | Medium |
| Remove K Digits | Increasing stack, pop bigger digits | Medium |
| Largest Rectangle in Histogram | First smaller bar on each side | Hard |
| Trapping Rain Water | Stack of bars, fill water when a taller wall arrives | Hard |
🎯 Spot the pattern: is it a monotonic stack?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. For each stock price, find how many consecutive days before it had a lower or equal price (stock span).
2. Find the next greater element for every number in a list.
3. Find the kth largest number in an array.
4. Find the largest rectangle in a histogram.
5. Check if brackets like ({[]}) are balanced.
🧠 PATH memory card
Remember the monotonic stack for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A line of people, each waiting for the first taller person ahead. When a tall person arrives, all the shorter ones waiting get their answer and leave.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Waiting room: bigger walks in, smaller walk out”
- Waiting room→The stack holds indexes still waiting for an answer
- Bigger walks in→A new item bigger than the top
- Smaller walk out→Pop them; the new item is their answer
- Then sit down→Push the new item; it waits too
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
[2, 1, 2, 4, 3]: push 2 · push 1 · 2 arrives → 1 pops (answer 2) · push 2 · 4 arrives → 2, 2 pop (answer 4) · push 4 · push 3 · end: 4 and 3 get −1. Answer [4, 2, 4, −1, −1]. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Using
ifinstead ofwhile. One arrival can answer many waiting items. - Pushing values when you need distances. Push indexes.
- Wrong comparison for duplicates. Decide whether equal values should pop (
<=) or wait (<).
Where to go next
The stack answered “who's next bigger”. What if you need the K biggest out of millions, or a live top-10? That's the job of a heap: heap and top-K problems.
Key takeaways
- ✓A monotonic stack keeps items in increasing or decreasing order.
- ✓It answers “next greater / smaller” for every element in one pass.
- ✓Pop while the new item beats the top; popped items get their answer.
- ✓Store indexes; each is pushed once and popped once: O(n).
- ✓Signals: next greater, days until warmer, stock span, histogram.
Frequently asked questions
What is a monotonic stack?
A stack whose items are always kept in increasing or decreasing order. Before pushing a new item, you pop everything that breaks the order. The items you pop have just found their answer, for example their next greater element.
When should I use a monotonic stack?
When a problem asks, for every element, about the next (or previous) greater or smaller element: next greater element, daily temperatures, stock span, largest rectangle in a histogram, trapping rain water. The words 'next greater', 'next warmer', 'first taller' are the signal.
Why is the monotonic stack O(n) when it has a loop inside a loop?
Every element is pushed onto the stack once and popped at most once. So across the whole run the inner while loop does at most n pops in total. That's O(n) time and O(n) space for the stack.
Should I store values or indexes on the stack?
Usually indexes. With an index you can read the value (nums[i]) and also compute distances (day − cold_day for daily temperatures) or fill the right slot in the answer array.
Increasing or decreasing stack: which one do I need?
For 'next greater', keep a decreasing stack (pop while the top is smaller than the new item). For 'next smaller', keep an increasing stack (pop while the top is bigger). Ask: what would make a waiting item stop waiting?
🧠 Quick check: monotonic stack
1. Which question is a monotonic-stack problem?
2. Stack holds days at 75°, 71°, 69°. A 72° day arrives. Which days pop?
3. What's the time complexity of next greater element with a monotonic stack?
4. At the end, some indexes are still on the stack. What's their answer?
Checking your access…