Statement▼
Given an array of integers, temperatures, that represents daily temperatures, return an array, output, where each element, output[i], indicates the number of days you need to wait after the output[i] to 0.
Constraints:
1≤ temperatures.length≤103 30≤ temperatures[i]≤100
Solution
A
The steps of the algorithm are as follows:
Create an array,
output, of the same length astemperaturesand initialize all its elements to 0.Initialize an empty stack to keep track of the indices of the temperatures.
Loop through each index i of the
temperaturesarray:While the stack is not empty and the current temperature,
temperatures[i], is greater than the temperature at the index stored at the top of the stack:Pop the top index from the stack.
Calculate the difference between the current index i and the popped index. This difference represents the number of days until a warmer temperature for the day at the popped index.
Store this difference in the
outputarray at the position of the popped index.
Push the current index i onto the stack to continue tracking temperatures for future comparisons.
After processing all the temperatures, the
outputarray will contain the number of days until a warmer temperature for each day. Return thisoutputarray as the result.
Let’s look at the following illustration to get a better understanding of the solution: