How to Solve Daily Temperatures Days Until Warmer in Python
Compute the number of days until a warmer temperature for each day using a monotonic stack.
Python code
18 linesdef daily_temperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i, temp in enumerate(temps):
while stack and temps[stack[-1]] < temp:
prev_idx = stack.pop()
result[prev_idx] = i - prev_idx
stack.append(i)
return result
if __name__ == "__main__":
temps = [73, 74, 75, 71, 69, 72, 76, 73]
days = daily_temperatures(temps)
print(temps)
print(days)
Output
[73, 74, 75, 71, 69, 72, 76, 73]
[1, 1, 4, 2, 1, 1, 0, 0]
How it works
The algorithm uses a stack to keep track of indices of temperatures that haven't found a warmer day yet. As we iterate through temperatures, we pop indices from the stack while the current temperature is warmer than the temperature at the stack's top. For each popped index, the difference between the current index and the popped index is the days until a warmer temperature. If no warmer temperature is found, the result remains 0. This approach runs in O(n) time because each index is pushed and popped at most once.
Common mistakes
- Forgetting to initialize the result list with zeros, leading to incorrect values for days with no warmer temperature.
- Using a stack of temperatures instead of indices, which makes it impossible to calculate the difference in days.
- Not using a while loop to pop all indices with a lower temperature, resulting in missed results.
Variations
- Use a list comprehension with a helper function to make the code more compact, though it may be less readable.
- Implement the same logic using a deque from collections for potentially faster append/pop operations.
Real-world use cases
- Predicting the next higher price in time series financial data for trading decisions.
- Finding the next greater element in arrays for stock span problems in algorithmic trading.
- Computing waiting times for server requests where each request waits for a higher-priority task.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.