#739

Daily Temperatures

Medium Monotonic stack of indexes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For each day, return how many days you must wait for a warmer temperature, or 0 if none comes.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each day, how many days until a warmer one?

Why this works: a stack of waiting days (cooler ones on top). A warmer day pops them and fills in their wait.

Example: [73, 74, 75, 71, 69, 72, 76]

74 answers 73 (1), 75 answers 74 (1)72 answers 69 (1) and 71 (2)76 answers 72 (1) and 75 (4)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing temperatures instead of indexes — you need the index to compute the wait.

Solve on LeetCode ↗
Complexity
  • Time: O(n) — each index is pushed and popped once.
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon