739 Daily Temperatures

Problem Statement

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

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

Approach

Using a stack to track the index of temperatures for which we have not found a higher temperature. Using while loop comparing temperatures and looking at stack to get the temperatures index. Using results array to reassign the difference of current i and index at result[index].

Solution

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

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

Questions

References

LC
NC

Monotonic Stack