Solution: Daily Temperatures
Let’s solve the Daily Temperatures problem using the Stacks pattern.
We'll cover the following
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:
temperatures.length
temperatures[i]
Solution
A
The steps of the algorithm are as follows:
Create an array,
output
, of the same length astemperatures
and 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
temperatures
array: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
output
array 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
output
array will contain the number of days until a warmer temperature for each day. Return thisoutput
array as the result.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.