Daily Temperatures

Find how many days until a warmer temperature for each day.

Pattern

Monotonic Stack

This problem follows the Monotonic Stack pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Maintain a decreasing stack of indices. Pop when current temp is higher.

Key Insight

A monotonic decreasing stack ensures each index is pushed and popped exactly once — when you pop, you've found the next warmer day.

Step-by-step

  1. 1Create a stack of indices
  2. 2Iterate through temperatures
  3. 3While the stack is non-empty and current temp > temp at stack top:
  4. 4Pop the index, calculate the difference (days until warmer)
  5. 5Push the current index onto the stack

Pseudocode

result = [0] * len(temperatures)
stack = []  # stores indices
for i, temp in enumerate(temperatures):
    while stack and temperatures[stack[-1]] < temp:
        j = stack.pop()
        result[j] = i - j
    stack.push(i)
return result
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Stack Problems

Master this pattern with YeetCode

Practice Daily Temperatures and similar Stack problems with flashcards. Build pattern recognition through active recall.

Practice this problem