Daily Temperatures — Monotonic Stack Next Greater Element [LC 739]
Advertisement
Problem Statement
Given an array temperatures, return an array answer where answer[i] is the number of days after day i until a warmer temperature. If no future day is warmer, answer[i] = 0.
Constraints:
1 <= temperatures.length <= 10^530 <= temperatures[i] <= 100
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]Why This Problem Matters
Daily Temperatures is the canonical introduction to the monotonic stack — one of the most valuable patterns in FAANG interviews. Amazon and Google use it directly; Meta and Microsoft use close variants. The brute-force O(n²) approach is trivially correct but times out at n = 10^5. The O(n) insight — a single warm day can resolve many waiting cooler days at once — is exactly the amortized thinking interviewers test.
Mastering this problem gives you the foundation for at least six others: Next Greater Element I and II (LC 496, 503), Online Stock Span (LC 901), Largest Rectangle in Histogram (LC 84), Maximal Rectangle (LC 85), and Trapping Rain Water (LC 42). All share the same "pop when the invariant breaks" structure.
The Core Insight
Use a monotonic decreasing stack of indices. The stack always holds indices whose temperatures are decreasing from bottom to top — each index is "waiting" for a future warmer day.
When processing day i:
- While the stack is non-empty and
temperatures[i] > temperatures[stack.top()]: pop indexj, setanswer[j] = i - j - Push
ionto the stack
After the full iteration, any index still in the stack never found a warmer day — its answer stays 0. Each index is pushed exactly once and popped at most once, making total work O(n) despite the nested while loop.
Visual Dry Run
Input: [73, 74, 75, 71, 69, 72, 76, 73]
| Step | i | temp | Stack state | Action |
|---|---|---|---|---|
| 0 | 0 | 73 | [] | push 0 |
| 1 | 1 | 74 | [0] | 74 greater than 73 — pop 0 ans[0]=1; push 1 |
| 2 | 2 | 75 | [1] | 75 greater than 74 — pop 1 ans[1]=1; push 2 |
| 3 | 3 | 71 | [2] | 71 less than 75 — push 3 |
| 4 | 4 | 69 | [2,3] | 69 less than 71 — push 4 |
| 5 | 5 | 72 | [2,3,4] | 72 greater than 69 pop 4 ans[4]=1; 72 greater than 71 pop 3 ans[3]=2; push 5 |
| 6 | 6 | 76 | [2,5] | 76 greater than 72 pop 5 ans[5]=1; 76 greater than 75 pop 2 ans[2]=4; push 6 |
| 7 | 7 | 73 | [6] | 73 less than 76 — push 7 |
Indices 6 and 7 remain in stack — no warmer day found, answer stays 0.
Final: [1,1,4,2,1,1,0,0]
Solution (Optimal)
class Solution:
def dailyTemperatures(self, temperatures):
n = len(temperatures)
answer = [0] * n
stack = [] # monotonic decreasing stack of indices
for i, temp in enumerate(temperatures):
while stack and temp > temperatures[stack[-1]]:
j = stack.pop()
answer[j] = i - j
stack.append(i)
return answervar dailyTemperatures = function(temperatures) {
const n = temperatures.length;
const answer = new Array(n).fill(0);
const stack = [];
for (let i = 0; i < n; i++) {
while (stack.length > 0 && temperatures[i] > temperatures[stack.at(-1)]) {
const j = stack.pop();
answer[j] = i - j;
}
stack.push(i);
}
return answer;
};Time: O(n) — each index pushed and popped at most once Space: O(n) — stack can hold all indices in worst case (strictly descending input)
Common Mistakes
- Storing temperatures in the stack instead of indices — you need the index to compute
i - j - Using a monotonic increasing stack — that finds "next cooler", not "next warmer"
- Using
>=instead of>— strictly warmer is required; equal temperatures must not pop - Returning -1 for days with no future warmer day — the problem requires 0
- Forgetting to initialize the answer array with zeros — remaining stack entries need 0
Interview Tips
- State the key insight: "one warm day can resolve many waiting cooler days, so total work is O(n)"
- Clarify upfront: store indices not temperatures, because you need position to compute the wait
- Draw stack state for a short example step by step — interviewers love visual dry runs
- Explain amortized O(n): each element does at most one push and one pop across the whole algorithm
- Mention this pattern directly solves Next Greater Element, Online Stock Span, and Histogram Rectangle
Follow-up Questions
- How would you solve this for a circular array — next greater wraps around? (Iterate 2n steps with
i % n, LC 503) - What if you want the previous warmer day instead of the next? (Iterate right to left with same stack logic)
- How does this generalize to "next smaller element"? (Use monotonic increasing stack, pop when current is smaller)
- Can you solve Online Stock Span using the same pattern? (Yes — monotonic decreasing stack of price-span pairs, LC 901)
- What is the worst-case space usage? (O(n) when input is strictly decreasing — every element waits forever)
Key Takeaways
- LeetCode 739 is the canonical monotonic stack problem, asked at Amazon, Google, and Meta
- A monotonic decreasing stack of indices solves "next greater element" in O(n) amortized time
- Always store indices in the stack, not values — index gives both position and value via lookup
- Pop when current temperature exceeds stack top; current day is the answer for everything popped
- Each element is pushed once and popped at most once — O(n) total work despite the nested while loop
- Zero-initialized answer array handles remaining stack entries automatically — no post-processing needed
- Mastering LC 739 directly unlocks six other problems: LC 496, 503, 84, 85, 42, and 901
Advertisement