The “Daily Temperatures” problem asks us to determine, for each day, how many days one must wait until a warmer temperature occurs. If there is no future day with a warmer temperature, the answer should be 0
for that day.
For example:
[73, 74, 75, 71, 69, 72, 76, 73]
[1, 1, 4, 2, 1, 1, 0, 0]
This problem is an excellent introduction to using monotonic stacks — stacks that maintain a specific order (in this case, decreasing temperatures). It's commonly used in interview questions to test your ability to efficiently track future or next-greater elements in a sequence.
Instead of checking each future day for a warmer temperature (which would be O(n²)), we can use a stack to track the indices of temperatures in decreasing order. When a warmer temperature is found, we resolve the earlier days stored in the stack.
answer
of the same length as the input, filled with 0
.i
:
temperatures[i] > temperatures[stack[top]]
:
i - popped_index
.answer[popped_index]
to that value.i
onto the stack.answer
array.
Input: [73, 74, 75, 71, 69, 72, 76, 73]
Stack keeps track of indices with unresolved temperatures:
Final answer: [1, 1, 4, 2, 1, 1, 0, 0]
Time Complexity: O(n), where n is the number of days. Each index is pushed and popped from the stack at most once.
Space Complexity: O(n) for the output array and the stack.
The “Daily Temperatures” problem is a classic use case for monotonic stacks. It teaches you how to efficiently handle problems where you're asked to find the next greater element or to track dependencies on future values. Understanding this approach builds a strong foundation for similar problems in array and stack manipulation.