Two approaches to LeetCode Daily Temperatures โ brute force O(nยฒ) and optimal monotonic stack O(n). Java and Python solutions with visual walkthrough.
LeetCode ยท #739
Daily Temperatures Solution
Given daily temperatures, return an array where answer[i] is the number of days until a warmer temperature. If no warmer day exists, answer[i] = 0.
Given an array of integers temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i-th day to get a warmer temperature. If there is no future day with a warmer temperature, set answer[i] = 0.
Example
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
// Day 0 (73ยฐ): next warmer is day 1 (74ยฐ) โ 1// Day 2 (75ยฐ): next warmer is day 6 (76ยฐ) โ 4 days
For each day, scan rightward to find the first warmer day. Record the distance.
Problem: O(n) scan per day โ O(nยฒ) total. A monotonic decreasing stack resolves all "waiting" days in one pass โ each day is pushed once and popped once for O(n).
Java โ Brute Force
classSolution {
publicint[] dailyTemperatures(int[] temps) {
int[] answer = newint[temps.length];
for (int i = 0; i < temps.length; i++)
for (int j = i + 1; j < temps.length; j++)
if (temps[j] > temps[i]) { answer[i] = j - i; break; }
return answer;
}
}
Python โ Brute Force
classSolution:
defdailyTemperatures(self, temps: list[int]) -> list[int]:
answer = [0] * len(temps)
for i in range(len(temps)):
for j in range(i + 1, len(temps)):
if temps[j] > temps[i]:
answer[i] = j - i
breakreturn answer
Metric
Value
Time
O(nยฒ)
Space
O(1) โ excluding output
03
Section Three ยท Approach 2
Monotonic Stack โ O(n)
Maintain a stack of indices representing days waiting for a warmer temperature. The stack is in decreasing temperature order. When a new day is warmer than the stack's top, pop and resolve โ the wait is current_index โ popped_index.
๐ก Mental model: Imagine a queue of people waiting for the sun to come out. When a warmer day arrives, everyone in the queue who was waiting for at least this much warmth steps out and records how long they waited. The remaining people (who need even more warmth) keep waiting. New arrivals join the back.
Algorithm
Step 1: Create an empty stack (stores indices, not temperatures).
Step 2: For each day i:
Step 3: While stack is non-empty AND temps[i] > temps[stack.peek()]: pop index j. Set answer[j] = i โ j.
Step 4: Push i onto the stack.
Step 5: Remaining stack indices get 0 (no warmer day) โ already initialized.
๐ฏ Monotonic stack pattern:
Any "next greater element" or "next smaller element" problem โ monotonic stack.
The stack maintains a decreasing (for next-greater) or increasing (for next-smaller) order.
When an element breaks the monotonicity, all violated elements get their answer.
Each element is pushed/popped exactly once โ O(n).
04
Section Four ยท Trace
Visual Walkthrough
Trace through temps = [73, 74, 75, 71, 69, 72, 76, 73]:
Monotonic Decreasing Stack โ pop when warmer day found
05
Section Five ยท Implementation
Code โ Java & Python
Java โ Monotonic Stack
import java.util.Stack;
classSolution {
publicint[] dailyTemperatures(int[] temperatures) {
int[] answer = newint[temperatures.length];
Stack<Integer> stack = newStack<>(); // indicesfor (int i = 0; i < temperatures.length; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int j = stack.pop();
answer[j] = i - j;
}
stack.push(i);
}
return answer; // remaining indices default to 0
}
}
Python โ Monotonic Stack
classSolution:
defdailyTemperatures(self, temperatures: list[int]) -> list[int]:
answer = [0] * len(temperatures)
stack = [] # indicesfor i, temp in enumerate(temperatures):
while stack and temp > temperatures[stack[-1]]:
j = stack.pop()
answer[j] = i - j
stack.append(i)
return answer
06
Section Six ยท Analysis
Complexity Analysis
Approach
Time
Space
Trade-off
Brute Force
O(nยฒ)
O(1)
Scan right for each day
Monotonic Stack โ optimal
O(n)
O(n)
Each index pushed/popped once. Stack holds waiting days.
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
Case
Input
Why It Matters
Decreasing
[76, 75, 74, 73]
No warmer days โ all zeros. Stack grows to size n.
Increasing
[73, 74, 75, 76]
Every day pops immediately โ all 1s except last (0).
All same
[70, 70, 70]
Equal is NOT warmer โ all zeros.
Single day
[73]
No future days โ [0].
Warmer at end
[73, 71, 69, 76]
Day 6 resolves all waiting days at once โ multiple pops.
โ Common Mistake: Using >= instead of > in the comparison. The problem asks for a strictly warmer day. If you pop on equal temperatures, you'll report a day that isn't actually warmer. Always use strict >.