💡
Exercise 73

Daily Temperatures 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an array of daily temperatures, return an array where answer[i] is the number of days you have to wait after day i for a warmer temperature. If there is no future day, put 0.

temperatures = [73, 74, 75, 71, 69, 72, 76, 73] # Output: [1, 1, 4, 2, 1, 1, 0, 0] # Day 0 (73°): next warmer is day 1 (74°) → wait 1 day # Day 2 (75°): next warmer is day 6 (76°) → wait 4 days # Day 6 (76°): no warmer day ahead → 0

This is a classic Monotonic Decreasing Stack problem:

  • Maintain a stack of indices (not values) where temperatures are decreasing
  • When you find a warmer temperature, pop all colder days from the stack
  • The wait time is current_index - popped_index
  • Time: O(n) — each index is pushed and popped at most once

Monotonic stacks are a powerful pattern — they appear in many interview problems!

📋 Instructions
Implement `daily_temperatures(temperatures)` using a monotonic stack. Test with [73, 74, 75, 71, 69, 72, 76, 73].
Use a stack of indices. For each day i, while the stack is not empty AND temps[i] > temps[stack[-1]], pop the index and set answer[popped] = i - popped. Then push i.
🧪 Test Cases
Input
result
Expected
[1, 1, 4, 2, 1, 1, 0, 0]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.