Daily Temperatures
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #739
Given daily temperatures, return an array where answer[i] is how many days you must wait after day i for a strictly warmer day. Use 0 if no warmer day comes.
Examples
text
[73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0]
[30, 60, 90] → [1, 1, 0]Hints
- Brute force scans forward from each day, O(n²).
- Keep a stack of days still waiting for a warmer day. Their temperatures are decreasing from bottom to top.
- When today is warmer than the stack top, that day's wait is over.
Approach
Iterate over days, keeping a stack of indices whose temperatures are strictly decreasing. For day i, while the top day is colder than temperatures[i], pop it and set its answer to i − top. Then push i. Days left on the stack never get warmer, so their answer stays 0. Step through it in the visualizer above.
Complexity
Time: O(n) amortized. Space: O(n).
Python solution
def dailyTemperatures(temperatures):
ans = [0] * len(temperatures)
st = []
for i, t in enumerate(temperatures):
while st and temperatures[st[-1]] < t:
j = st.pop()
ans[j] = i - j
st.append(i)
return ansJavaScript solution
function dailyTemperatures(temperatures) {
const ans = new Array(temperatures.length).fill(0), st = [];
for (let i = 0; i < temperatures.length; i++) {
while (st.length && temperatures[st[st.length - 1]] < temperatures[i]) {
const j = st.pop();
ans[j] = i - j;
}
st.push(i);
}
return ans;
}