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, put 0 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
2
Input:  [73, 74, 75, 71, 69, 72, 76, 73]
Output: [ 1, 1, 4, 2, 1, 1, 0, 0]

Follow up:

Analysis

Brute-Force

For each temperature, we find its first strictly increasing temperature.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int[] dailyTemperatures(int[] T) {
int n = T.length;
int[] result = new int[n];
for (int i = 0; i < n; ++i) {
int day = 0;
int j = i;
while (j < n && T[i] >= T[j]) {
++j;
++day;
}
result[i] = (j == n) ? 0 : day;
}
return result;
}

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
2
3
4
5
6
7
8
9
10
11
12
13
public int[] dailyTemperatures(int[] T) {
int n = T.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; --i) {
while (stack.size() > 0 && T[i] >= T[stack.peek()]) { // pop unsatisfied values
stack.pop();
}
result[i] = stack.size() > 0 ? stack.peek() - i : 0;
stack.push(i);
}
return result;
}

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.