Daily Temperatures - Problem

Given an array of integers temperatures representing the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i-th day to get a warmer temperature.

If there is no future day for which this is possible, keep answer[i] == 0 instead.

Input & Output

Example 1 — Basic Case
$ Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
💡 Note: Day 0 (73°): Next warmer is day 1 (74°) → wait 1 day. Day 1 (74°): Next warmer is day 2 (75°) → wait 1 day. Day 2 (75°): Next warmer is day 6 (76°) → wait 4 days. Day 6 and 7 have no warmer days → 0.
Example 2 — Single Temperature
$ Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
💡 Note: Each day has the next day warmer except the last day: 30→40 (wait 1), 40→50 (wait 1), 50→60 (wait 1), 60→none (wait 0).
Example 3 — Decreasing Temperatures
$ Input: temperatures = [30,60,90]
Output: [1,1,0]
💡 Note: Day 0: Next warmer at day 1 → wait 1. Day 1: Next warmer at day 2 → wait 1. Day 2: No warmer day → wait 0.

Constraints

  • 1 ≤ temperatures.length ≤ 105
  • 30 ≤ temperatures[i] ≤ 100

Visualization

Tap to expand
Daily Temperatures - Stack Solution INPUT temperatures array 0 1 2 3 4 5 6 7 73 74 75 71 69 72 76 73 Temperature Visualization Find days until warmer For each day, count how many days until a warmer temp Day 0: 73 --> 74 = 1 day Day 2: 75 --> 76 = 4 days Day 6: 76 --> none = 0 days ALGORITHM STEPS 1 Initialize Stack Stack stores indices of unresolved days 2 Iterate Array Process each temperature left to right 3 Pop Smaller Temps While current > stack top, pop and calculate difference (answer) 4 Push Current Index Add current index to stack Stack State Example (i=5, temp=72) Stack (indices) 2 (75) 3 (71) POP 4 (69) POP 72 > 69: answer[4] = 5-4 = 1 72 > 71: answer[3] = 5-3 = 2 FINAL RESULT answer array (days to wait) 0 1 2 3 4 5 6 7 1 1 4 2 1 1 0 0 Result Breakdown: Day 0 (73): wait 1 day for 74 Day 1 (74): wait 1 day for 75 Day 2 (75): wait 4 days for 76 Day 3 (71): wait 2 days for 72 Day 4 (69): wait 1 day for 72 Day 5 (72): wait 1 day for 76 Day 6 (76): no warmer day (0) Day 7 (73): no warmer day (0) Complexity Analysis Time: O(n) Space: O(n) OK Key Insight: Monotonic Decreasing Stack: The stack maintains indices in decreasing temperature order. When we find a warmer temperature, we pop all cooler days and calculate their waiting time. Each element is pushed and popped at most once, giving us O(n) time complexity. This is optimal compared to O(n^2) brute force approach. TutorialsPoint - Daily Temperatures | Optimal Solution (Monotonic Stack)
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
255.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen