Learning Outcome
After this lesson, you should be able to use a monotonic stack to resolve "next greater" style questions in one pass.
Problem Statement
Given daily temperatures, return an array where each value tells how many days you must wait for a warmer temperature. If there is no future warmer day, use 0.
| Input | Output | Why |
|---|---|---|
[73,74,75,71,69,72,76,73] | [1,1,4,2,1,1,0,0] | For day 2 at 75, the next warmer day is 4 days later at 76. |
Brute Force Approach
For each day, scan all later days until a warmer temperature is found.
This is clear, but in the worst case it costs O(n^2).
Optimized Approach
Keep a stack of indices whose warmer day has not been found yet. The stack is decreasing by temperature. When the current temperature is warmer than the temperature at the stack top, pop that index and fill its answer.
Exact Pseudocode
answer = array of zeroes
stack = empty stack of indices
for i from 0 to length(temperatures) - 1:
while stack is not empty and temperatures[i] > temperatures[stack.top]:
prev = pop stack
answer[prev] = i - prev
push i
return answer
Reference Code
class Solution:
def dailyTemperatures(self, temperatures):
answer = [0] * len(temperatures)
stack = []
for i, temp in enumerate(temperatures):
while stack and temp > temperatures[stack[-1]]:
prev = stack.pop()
answer[prev] = i - prev
stack.append(i)
return answerSample Dry Run
| day | temp | stack before | Action |
|---|---|---|---|
| 0 | 73 | [] | Push 0 |
| 1 | 74 | [0] | 74 warms day 0, answer[0] = 1, push 1 |
| 2 | 75 | [1] | 75 warms day 1, answer[1] = 1, push 2 |
| 3 | 71 | [2] | Not warmer than 75, push 3 |
| 5 | 72 | [2,3,4] | Resolve days 4 and 3 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Each index is pushed once and popped once. |
| Space | O(n) | The stack may hold many unresolved days. |
Edge Cases
- Strictly decreasing temperatures produce all zeroes.
- Equal temperatures are not warmer.
- Single-day input returns
[0].
Interview Checklist
- Store indices, not temperatures, so you can compute distance.
- Use
>, not>=, because equal is not warmer. - Leave unresolved days as zero.
FAQs
Why is this a monotonic stack?
The stack keeps unresolved days in decreasing temperature order.
Why store indices?
The answer requires the number of days waited, which is the current index minus the previous index.
What is the core pattern?
Next greater element with a monotonic stack.