Daily Temperatures
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0.
- 1 <= temperatures.length <= 10⁵
- 30 <= temperatures[i] <= 100
temperatures = [73,74,75,71,69,72,76,73][1,1,4,2,1,1,0,0]temperatures = [30,40,50,60][1,1,1,0]For each day we want the number of days until a warmer one. The direct approach — from each day, scan forward until the temperature rises — is fine until you hit a long cool spell, where every day marches down the same tail of cooler days that the day before already walked. On a slowly warming-then-cooling season that's about N²/2 comparisons, nearly all of them repeats.
The fix rests on one observation: while you scan forward, a day is still "unanswered" only as long as nothing warmer has come along. That means the unanswered days, read from oldest to newest, always have falling temperatures — if a newer unanswered day were warmer than an older one, it would already have answered that older day when it arrived. A stack whose contents are guaranteed to stay in order like this is a monotonic stack: a plain push/pop stack with the rule that its values only ever decrease from bottom to top.
Store day indices, not the temperatures — the answer is a distance, and with indices the distance is just today - waiting_day. Scan the days in order: while today is warmer than the day sitting on top of the stack, today is that day's warmer future, so record i - popped and pop it. One warm day can settle a whole run of cooler days stacked beneath it. When the top is warmer than today (or the stack is empty), today pushes on and waits its turn.
# Monotonic Stack (O(N) Time, O(N) Space)
n = len(temperatures)
res = [0] * n
stack = [] # holds day indices; temps kept decreasing
for i in range(n):
while stack and temperatures[i] > temperatures[stack[-1]]:
prev = stack.pop()
res[prev] = i - prev # warmer day found, 'i - prev' days later
stack.append(i)
return resEach day is pushed once and popped at most once, so the total work is linear even with the inner loop. Any day still on the stack at the end never saw a warmer day again, and its answer stays at the default 0.
[0]1-0=1; pop, push 1. Stack: [1]2-1=1; pop, push 2. Stack: [2][2, 3][2, 3, 4][1, 1, 0, 0, 0].Finding the Next Greater Element in Linear Time
How it Works
We use a stack to store indices of temperatures we haven't found a warmer day for yet.
When we see a temperature warmer than the stack top, we pop the index and calculate the difference.
The stack stays monotonic (always decreasing temperatures) because any higher value immediately clears out lower ones.
Complexity Insight
This runs in O(N) time because each temperature is pushed and popped exactly once. Using a stack converts a nested search into a single linear pass.