1 April 2024

Medium

739. Daily Temperatures

Link: https://leetcode.com/problems/daily-temperatures

Description: Given a list of daily temperatures, return a list of the number of days you would have to wait until a warmer temperature. If there is no warmer temperature, return 0.

Solution:

Use a stack to keep track of the indices of the temperatures. Iterate through the temperatures and compare the current temperature with the temperature at the top of the stack. If the current temperature is greater than the temperature at the top of the stack, calculate the difference in days and update the answer array. Continue this process until the stack is empty or the current temperature is not greater than the temperature at the top of the stack. Push the current index onto the stack.

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function (temperatures) {
  let answer = new Array(temperatures.length).fill(0)
  let stack = []

  for (let i = 0; i < temperatures.length; i++) {
    // Check if current temp is greater than temp at top of the stack
    while (
      stack.length > 0 &&
      temperatures[i] > temperatures[stack[stack.length - 1]]
    ) {
      let index = stack.pop() // Pop the index of the colder day
      answer[index] = i - index // Calculate the difference in days
    }
    stack.push(i) // Push the current day's index onto the stack
  }

  return answer
}