Video in progress

Strong Middle 🧠 Problem solving

For each day's temperature, how do you find in O(n) how many days later a warmer day comes?

With a monotonic stack: I keep on the stack the indexes of days whose answer hasn't been found yet, in decreasing temperature order. If a new day is warmer than the one at the top, that day's answer is found: I pop it and record the difference. Each index goes in once and comes out once.

📖 Answer

[73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0].

static int[] daysUntilWarmer(int[] t) {
    int[] ans = new int[t.length];
    Deque<Integer> stack = new ArrayDeque<>();   // indexes
    for (int i = 0; i < t.length; i++) {
        while (!stack.isEmpty() && t[stack.peek()] < t[i]) {
            int j = stack.pop();
            ans[j] = i - j;
        }
        stack.push(i);
    }
    return ans;   // 0 for those left on the stack
}

There is a while inside, but the complexity isn't O(n²). Each index is pushed onto the stack once and popped at most once, so 2n operations in total. This is an amortization argument, and you should definitely say it in the interview.

Why indexes on the stack and not values? The answer is a distance, and computing it needs the index. The value can always be read from the array by index.

This template solves the whole "next greater element" family: the largest rectangle in a histogram, "how much rain water is trapped", a stock price "span". If you reverse the comparison (>), you get "next smaller".