Engineered
Data Structures

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

mediumStack · Monotonic Stack30 minLC 739
Problem

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:

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

Example 2:

Input: temperatures = [30, 40, 50, 60]
Output: [1, 1, 1, 0]

Constraints

  • 1 ≤ temperatures.length ≤ 100,000
  • 30 ≤ temperatures[i] ≤ 100
0 attempts

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

MeasureComplexityExplanation
TimeO(n)Every index is pushed once and popped at most once.
Auxiliary spaceO(n)A decreasing sequence leaves every index in the stack.

How is this lesson?