Daily Temperatures
You're given an array temperatures where temperatures[i] is the temperature on day i. Return an array answer of the same length where answer[i] is how many days after day i you have to wait for a strictly warmer temperature. If no later day is warmer, answer[i] is 0. A later day with the same temperature does not count as warmer.
Examples
temperatures = [73,74,75,71,69,72,76,73] returns [1,1,4,2,1,1,0,0]
Day 0 (73) is followed right away by a warmer 74, so it waits 1 day. Day 2 (75) sits through 71, 69 and 72 before 76 arrives on day 6, a wait of 4. Days 6 and 7 never see anything warmer, so they get 0.
temperatures = [30,40,50,60] returns [1,1,1,0]
Every day is warmer than the one before, so each of the first three days waits exactly 1 day. The last day has no later day at all, so it gets 0.
temperatures = [71,71,72] returns [2,1,0]
Day 1 ties day 0 at 71, which is not warmer, so day 0 waits until 72 on day 2, a wait of 2. Day 1 waits 1 day for the same 72.
Constraints
- 1 <= temperatures.length <= 10^5
Hints
For each day, you're looking for the next strictly warmer day, could you process days while pending ones wait their turn?
Maintain a stack of indices with strictly decreasing temperatures.
Iterate over temperatures. While the stack is non-empty and the current temperature is greater than temps[stack.top()], pop that index j and set answer[j] = i - j. Push i. Indices left on the stack at the end keep answer[j] = 0.
Drill This: Your Approach First
Approach
Keep a stack of indices of days still waiting for a warmer day; their temperatures never increase from bottom to top. When day i arrives, pop every waiting day j with temperatures[j] < temperatures[i] and set answer[j] = i - j, since i is the first warmer day after j. Then push i. Days left on the stack at the end keep 0. Each index is pushed and popped at most once, so the pass is linear.
Time
O(n)
Space
O(n)
Pitfall
Solutions
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] result = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
int j = stack.pop();
result[j] = i - j;
}
stack.push(i);
}
return result;
}
}class Solution:
def dailyTemperatures(self, temperatures):
n = len(temperatures)
result = [0] * n
stack = []
for i, t in enumerate(temperatures):
while stack and temperatures[stack[-1]] < t:
j = stack.pop()
result[j] = i - j
stack.append(i)
return result