#739. Daily Temperatures

ยท

1 min read

https://leetcode.com/problems/daily-temperatures/description/?envType=daily-question&envId=2024-01-31


var dailyTemperatures = function (temperatures) {
    const result = new Array(temperatures.length).fill(0)
    const stack = []

    for (let i = 0; i < temperatures.length; i++) {
        while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
            const prevIdx = stack.pop()
            result[prevIdx] = i - prevIdx
        }
        stack.push(i)
    }

    return result
};

We have an array of values that represents temperatures, for every temperature, we go through the array to find a greater one, once we find a value greater than the temperature we are currently at to the right of it, we subtract the indices of the two and push it to a result array mapped to every value in temperature array.

Eventually, the result array is returned as our answer.

ย