Days Until Higher Temperature
Stacks & QueuesAuto-graded · 26 test casesLast updated
Tests efficient computation of the distance to the next strictly greater element using a monotonic stack to achieve linear time complexity.
You are given an array of integers temperatures where each element represents the temperature recorded on a particular day.
For each day in the array, determine how many days into the future you must look to find a strictly higher temperature. If no such day exists, the result for that position should be 0.
Return an array of integers where each element represents the number of days to wait for a warmer temperature from the corresponding day in the input.
Constraints
1 <= len(temperatures) <= 10^530 <= temperatures[i] <= 100- Equal temperatures do not count as "warmer" — you must find a strictly greater value
Examples
Example 1
Input: days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73])
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Example 2
Input: days_until_warmer([30, 40, 50, 60])
Output: [1, 1, 1, 0]
Example 3
Input: days_until_warmer([90, 80, 70])
Output: [0, 0, 0]
Hints
Hint 1
Think about what information you need to track as you scan through the array from left to right.
Hint 2
A stack can help you keep track of days that haven't yet found their warmer day. What should you store in the stack?
Hint 3
When you encounter a new temperature, it might resolve multiple previous days at once. How can you efficiently find all the days it resolves?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is finding the next strictly greater element for each position efficiently. A brute-force nested loop checking every future day would take O(n²) time, which is too slow for arrays up to 10⁵ elements.
The optimal solution uses a monotonic stack that stores indices of days that haven't yet found a warmer temperature. Process the array from left to right:
- Initialize a result array filled with zeros (the default when no warmer day exists)
- Maintain a stack of indices representing "unresolved" days
- For each current day with temperature T:
- While the stack is not empty and the temperature at the top index is strictly less than T, this current day is the answer for that earlier day. Pop the index and record the difference
current_index - popped_index - Push the current index onto the stack
- While the stack is not empty and the temperature at the top index is strictly less than T, this current day is the answer for that earlier day. Pop the index and record the difference
- Any indices remaining on the stack after processing all days have no warmer future day, and their result stays 0
Why It Works
The stack maintains indices in order where their corresponding temperatures are non-increasing from bottom to top. This invariant ensures that when we encounter a temperature that is warmer than the stack top, it must be the first warmer day for that position—any days in between would have already popped it if they were warmer.
The strict less-than comparison (temperatures[stack[-1]] < temp) ensures that equal temperatures don't resolve each other, matching the requirement for strictly warmer days.
Complexity Analysis
Time Complexity: O(n)
Although there's a while loop inside the for loop, each index is pushed exactly once and popped at most once throughout the entire algorithm. This gives us at most 2n total stack operations, resulting in amortized O(n) time.
Space Complexity: O(n)
The result array requires O(n) space. The stack can grow to O(n) in the worst case (for example, when temperatures are strictly decreasing, all indices remain on the stack until the end).
Solution Code
from typing import List
def days_until_warmer(temperatures: List[int]) -> List[int]:
n = len(temperatures)
result = [0] * n
stack = []
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
prev_idx = stack.pop()
result[prev_idx] = i - prev_idx
stack.append(i)
return result
Key implementation details:
- Store indices in the stack, not temperatures, because we need the index to compute the day difference
- Initialize the result with zeros so unresolved days automatically have the correct answer
- Use strict less-than (
<) to ensure equal temperatures don't count as warmer