Daily Temperatures
Master this topic with zero to advance depth.
Daily Temperatures
Given an array of integers 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, keep answer[i] == 0.
Visual Representation
temps = [73, 74, 75, 71, 69, 72, 76, 73]
Stack (indices of waiting days):
1. i=0 (73): Push 0. Stack: [0]
2. i=1 (74): 74 > 73. Pop 0, ans[0]=1-0=1. Push 1. Stack: [1]
3. i=2 (75): 75 > 74. Pop 1, ans[1]=2-1=1. Push 2. Stack: [2]
4. i=3 (71): Push 3. Stack: [2, 3]
5. i=4 (69): Push 4. Stack: [2, 3, 4]
6. i=5 (72): 72 > 69. Pop 4, ans[4]=1. 72 > 71. Pop 3, ans[3]=2. Stack: [2, 5]
7. i=6 (76): 76 > 72. Pop 5, ans[5]=1. 76 > 75. Pop 2, ans[2]=4. Stack: [6]Examples
Level I: Brute Force (Nested Loops)
Intuition
For each day, simply look ahead to the right to find the first day with a higher temperature. This is the most natural approach but is slow for large inputs.
Level III: Optimal (Monotonic Stack)
Intuition
Use a stack to store indices of temperatures that haven't found a warmer day yet. As we iterate, if the current temperature is warmer than the temperature at the index on top of the stack, we've found our 'warmer day' for that index. This efficiently ensures each element is pushed/popped once.
Detailed Dry Run
| i | Temp | Action | Stack Status | ans[idx] |
|---|---|---|---|---|
| 3 | 71 | Push | [2, 3] | - |
| 4 | 69 | Push | [2, 3, 4] | - |
| 5 | 72 | Pop 4, Pop 3 | [2, 5] | ans[4]=1, ans[3]=2 |
| 6 | 76 | Pop 5, Pop 2 | [6] | ans[5]=1, ans[2]=4 |
⚠️ Common Pitfalls & Tips
Remember that the stack should store indices, not values, so you can calculate the distance between days.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.