Daily Temperatures
Use a monotonic stack to find the next warmer day.
Try It Yourself
Use the editor below to calculate how many days each temperature waits for a warmer value. Store indices whose answer has not yet been found.
Submit your implementation when it passes the examples. Equal temperatures are not warmer, and some days may never receive an answer.
Daily Temperatures
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.
Example 1:
Example 2:
Constraints
1 ≤ temperatures.length ≤ 100,00030 ≤ temperatures[i] ≤ 100
Solution
Keep a stack of unresolved indices whose temperatures decrease from bottom to top. A new warmer temperature resolves every cooler index at the top.
Pop each resolved index and store the distance to the current day. Indices left in the stack keep the default answer of zero.
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;
}Big O notation
| 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. |