← Back to DSA Animator
Daily Temperatures LC #739 Medium Monotonic Stack
Problem

Given an array of integers temperatures representing 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 with a warmer temperature, keep answer[i] == 0.

Example 1
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Explanation: Day 2 (75°) waits 4 days for day 6 (76°). Day 3 (71°) waits 2 days for day 5 (72°).
Example 2
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3
Input: temperatures = [30,60,90]
Output: [1,1,0]
Constraints: 1 ≤ temperatures.length ≤ 10⁵  |  30 ≤ temperatures[i] ≤ 100
Try Examples
Custom:
Approach
Monotonic Decreasing Stack: store indices of unresolved days
When temps[i] > temps[stack.top], pop stack and record the wait: ans[idx] = i − idx
Temperature Bar Chart
Monotonic Stack (indices)
top: empty
Stack is empty
Answer Array
Variables
Index i
temps[i]
Stack Top
ans[i]
Step Logic
Press ▶ Play or Next Step to begin the animation.
🌡️
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init ans[0..n-1] = 0, empty stack (stores indices)
2
For each i: while stack not empty and temps[i] > temps[stack.top]
3
Pop idx from stack; set ans[idx] = i − idx (days to wait)
4
Push i onto stack (unresolved day)
5
Remaining indices on stack: no warmer day → ans stays 0
Time
O(n)
Space
O(n)
Why Monotonic Stack Works

We maintain a stack of indices whose temperatures are in decreasing order. When we encounter a warmer day i, any stacked index j with temps[j] < temps[i] has found its answer: ans[j] = i − j. Each index is pushed and popped at most once, giving O(n) overall.