☰ All problems

26. Daily Temperatures

MediumArrayStack

You are given an array temperatures where temperatures[i] is the temperature recorded on day i.

Return an array answer of the same length where answer[i] is the number of days you would have to wait after day i to see a strictly warmer temperature. If no later day is warmer, answer[i] is 0.

Example 1
Input: temperatures = [70,72,68,65,69,75]
Output: [1,4,2,1,1,0]

Explanation: After day 1 (72) the next warmer day is day 5 (75), four days later. Day 5 is the last day, so it gets 0.

Example 2
Input: temperatures = [50,50,50]
Output: [0,0,0]

Explanation: An equal temperature does not count as warmer.

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

Constraints

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100
💡 Hint 1

Checking every later day for each day is O(n²). Can one pass settle several days at once?

💡 Hint 2

Keep the indices of days that are still waiting for a warmer day. Their temperatures are non-increasing from bottom to top.

💡 Hint 3

When today is warmer than the day on top of that stack, today is the answer for that day: pop it and record the distance.

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
function dailyTemperatures(temperatures) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc