Use a monotonic stack to find the next warmer day.
Use the editor below to calculate how many days each temperature waits for a warmer value.
Track days waiting for a warmer temperature
Store the indices of days still waiting. Equal temperatures do not end the wait. Use 0 for days with no warmer future temperature.
Submit your implementation when it passes the examples.
Given daily temperatures, return an array where each position contains the number of days until a warmer temperature.
Use 0 when no warmer future day exists.
1 ≤ temperatures.length ≤ 100,00030 ≤ temperatures[i] ≤ 100Results appear here after a run.
Keep unresolved day indices on a stack. From bottom to top, their temperatures stay the same or decrease. An equal reading leaves both days waiting because a match must be strictly warmer.
For [70, 70, 71], days 0 and 1 are both waiting when day 2 arrives. Pop day 1 and record 2 - 1 = 1, then pop day 0 and record 2 - 0 = 2. Day 2 has no warmer successor, so its answer stays zero. The result is [2, 1, 0].
function dailyTemperatures(temperatures) {
const answer = Array(temperatures.length).fill(0);
const stack = [];
for (let day = 0; day < temperatures.length; day++) {
while (
stack.length > 0 &&
temperatures[day] > temperatures[stack[stack.length - 1]]
) {
const previousDay = stack.pop();
answer[previousDay] = day - previousDay;
}
stack.push(day);
}
return answer;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Every index is pushed once and popped at most once. |
| Auxiliary space | O(n) | A decreasing sequence leaves every index in the stack. |