Skip to main content
Medium Stack High frequency

Daily Temperatures

Open on LeetCode

Approach Summary

Monotonic decreasing stack of indices. When current temp > stack top temp, pop and record the wait time.

Full Solution & Approach

For each day you want the next warmer day — the classic next-greater-element problem with distances instead of values. A monotonic decreasing stack of indices does it in one pass. Iterate through the array; while the stack is non-empty and the current temperature is warmer than the temperature at the index on top of the stack, the current day is the answer for that top index — pop it and record the difference. Then push the current index. The stack stays strictly decreasing in temperature from bottom to top, which guarantees that when a warmer day arrives it correctly resolves every index it can. Each index is pushed once and popped once, so the total work is linear. The monotonic-stack pattern — a stack that pops when the invariant breaks — is the same machinery behind largest-rectangle and next-greater-element, and recognizing it turns O(n²) "scan right for each element" into O(n).

Each index enters and leaves the stack exactly once — O(n) time. The stack holds up to n indices — O(n) space.

Solution Code

Solution

def daily_temperatures(temperatures: list[int]) -> list[int]:
    n = len(temperatures)
    res = [0] * n
    stack = []
    for i in range(n):
        while stack and temperatures[i] > temperatures[stack[-1]]:
            j = stack.pop()
            res[j] = i - j
        stack.append(i)
    return res

Edge Cases to Watch

  • Monotonically decreasing temperatures — all answers are 0
  • Monotonically increasing temperatures — every answer is 1
  • The hottest day — always 0
  • Equal temperatures — the strict comparison means equal days do not resolve each other

How to Recognize This Pattern

  • Next greater element with distance
  • Days until warmer

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Stack Monotonic Stack

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee