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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

18 lines
Python 3.9+
def 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

stdout
[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

  1. Use a list comprehension with a helper function to make the code more compact, though it may be less readable.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.