Reference: LeetCode
Difficulty: Medium
Problem
Given a list of daily temperatures
T
, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put0
instead.
Note: The length
of temperatures will be in the range [1, 30000]
. Each temperature will be an integer in the range [30, 100]
.
Example:
1 | Input: [73, 74, 75, 71, 69, 72, 76, 73] |
Follow up:
Analysis
Brute-Force
For each temperature, we find its first strictly increasing temperature.
1 | public int[] dailyTemperatures(int[] T) { |
Time: $O(N^2)$
Space: $O(1)$
Stack
We use a stack to keep track of a list of strictly increasing temperatures.
From LeetCode solution:
Note: Check stack’s size before popping.
1 | public int[] dailyTemperatures(int[] T) { |
Time: $O(N)$ since each index gets pushed ad popped at most once from the stack. good!
Space: $O(W)$ where $W$ is the size of the stack bounded by the number of temperatures that are strictly increasing.