Link: 739. Daily Temperatures
Track: Tiktok Tag
Question
Restate the problem
- Given an integer array
temperatures, wheretemperatures[i]is the temperature on dayi - For each day
i, find the number of days until a warmer temperature occurs.- If there is no future day with a warmer temperature,
answer[i] = 0.
- If there is no future day with a warmer temperature,
- Return answer
Method 1 - stack
Method 1 - Monotonic Stack
Approach
Stackto stores indicesidx- Temperatures on those indices are strictly decreasing
- While
temp>stack[-1]the day at stack top, we can resolve that previous day:pre_idx = stack.pop()ans[pre_idx] = idx - pre_idx
Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
Edge Case
temperatures = []→ return[]- Strictly decreasing:
[80, 79, 78]→[0, 0, 0](no one gets popped)
Code
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
ans = [0] * len(temperatures)
for idx, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
pre_idx = stack.pop()
ans[pre_idx] = idx - pre_idx
stack.append(idx)
return ansHistory
- Feb-11-2026 Peeked