Sweaty Imposter

Daily Temperatures

MediumMonotonic Stack/QueueNeetCode 150MidOpen on LeetCodeUpdated

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]

7374757169727673
Day 2 (75) waits 4 days, until day 6 (76).

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

Hint 1

For each day, you're looking for the next strictly warmer day, could you process days while pending ones wait their turn?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

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

Popping on <= instead of < counts an equal temperature as warmer, so [71,71,72] comes out as [1,1,0] instead of [2,1,0]. Push indices, not temperatures, or you can't compute the wait i - j.

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;
    }
}
Drill This