Daily Temperatures Problem
Description
LeetCode Problem 739.
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 i^th day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
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^5
- 30 <=temperatures[i] <= 100
Solution
Approach: Monotonic Stack
For each day, scanning forward for the next warmer day is O(n2) on a long run of falling temperatures. Instead, turn it around: walk the days once, and let each day answer the earlier days it is warmer than.
Keep a stack waiting of the days (indices) that have not found a warmer day yet. For each day:
- While the day on top of the stack is colder than today, pop it. Today is its first warmer day, so its answer is
day - colderDay. - Push
dayonto the stack.
Days still on the stack at the end never see a warmer day and keep the answer 0.
The stack's temperatures never increase from bottom to top: a day is only pushed after every colder day above it has been popped. That is why popping can stop at the first day that is not colder: every day below it is at least as warm.
The comparison is strictly colder (<). A day with the same temperature is not warmer, so in [70, 70, 71] both 70s stay on the stack until 71 answers them with 2 and 1.
Example with [73, 74, 75, 71, 69, 72]: when 72 arrives, the stack holds the days of 75, 71, 69. It pops 69 (answer 1) and 71 (answer 2), stops at 75, and pushes 72.
Complexity: O(n) time, where n is the length of temperatures: each day is pushed and popped at most once. O(n) space for the stack.
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
answer = [0] * len(temperatures)
waiting = [] # indices of days still waiting for a warmer day; their temperatures never increase
for day, temp in enumerate(temperatures):
# Today is the warmer day for every waiting day that is colder.
while waiting and temperatures[waiting[-1]] < temp:
colder_day = waiting.pop()
answer[colder_day] = day - colder_day
waiting.append(day)
return answer # days left in `waiting` keep 0