Skip to problem
←

Daily Temperatures

Medium 0 attempts

You're given a list of daily temperatures. For each day, work out how many days you'd need to wait before a warmer day arrives, placing that count at the matching index of the result; if no later day is ever warmer, use 0 instead.

Function contract

Implement dailyTemperatures(temperatures), where temperatures[i] is the reading on day i.

Output: An array of the same length containing the number of days until the first strictly warmer reading. Use 0 if no such later day exists.

Example 1

Input
temperatures = [73,74,75,71,69,72,76,73]
Output
[1,1,4,2,1,1,0,0]

Example 2

Input
temperatures = [100,90,80]
Output
[0,0,0]
Constraints
  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100
Topics

Monotonic Stack

Maintain unresolved day indices with non-increasing temperatures; equal readings stay on the stack. A strictly warmer reading resolves each cooler top index. Every index is pushed once and popped at most once, giving linear total work.

javascript
function dailyTemperatures(temperatures) {
  const n = temperatures.length, ans = Array(n).fill(0), stack = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && temperatures[i] > temperatures[stack[stack.length-1]]) {
      const j = stack.pop(); ans[j] = i - j;
    }
    stack.push(i);
  }
  return ans;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript