Temperature Tracker - Problem

Given an array of daily temperatures, return an array where each element represents the number of days you have to wait until a warmer temperature arrives. If there is no future day with a warmer temperature, use 0 instead.

Use a monotonic stack approach to solve this efficiently. The stack should maintain temperatures in decreasing order and help track indices of days waiting for warmer weather.

Example: For temperatures [73, 74, 75, 71, 69, 72, 76, 73], the output should be [1, 1, 4, 2, 1, 1, 0, 0] because day 0 (73°) finds a warmer day after 1 day (74°), day 2 (75°) finds a warmer day after 4 days (76°), and so on.

Input & Output

Example 1 — Basic Temperature Sequence
$ 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 day is day 1 (74°) → wait 1 day. Day 1 (74°): next warmer day is day 2 (75°) → wait 1 day. Day 2 (75°): next warmer day is day 6 (76°) → wait 4 days. Day 6 and 7 have no warmer days ahead → 0.
Example 2 — Increasing Sequence
$ Input: temperatures = [30, 40, 50, 60]
Output: [1, 1, 1, 0]
💡 Note: Each day finds a warmer day immediately next, except the last day which has no future days.
Example 3 — Decreasing Sequence
$ Input: temperatures = [30, 60, 90]
Output: [1, 1, 0]
💡 Note: Day 0 finds warmer day 1, day 1 finds warmer day 2, day 2 has no warmer days ahead.

Constraints

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

Visualization

Tap to expand
INPUTALGORITHMRESULTDaily Temperatures73747571697276738 days of temperature data1Use monotonic stack2Track decreasing temps3Pop when warmer found4Calculate wait timesStack maintains indices withdecreasing temperaturesWait Days Array[1,1,4,2,1,1,0,0]Day 0: wait 1 day for 74°Day 1: wait 1 day for 75°Day 2: wait 4 days for 76°Days 6,7: no warmer daysKey Insight:Monotonic stack resolves multiple waiting days efficiently when warmer weather arrivesinstead of each day scanning forward independently. Time: O(n), Space: O(n)TutorialsPoint - Temperature Tracker | Monotonic Stack Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
89.0K Views
High Frequency
~15 min Avg. Time
2.4K 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