↻one more pass.
Stack · Medium

Daily Temperatures: the idea to remember.

For each day return the number of days until a strictly warmer temperature, or zero.

Solve on LeetCode ↗

The core insight

Keep unresolved indices in a stack with nonincreasing temperatures.

Why it works

A new warmer day resolves all smaller temperatures at the stack top, and is their first warmer day.

The mistake to avoid

Store indices to compute distances. Equal temperatures do not resolve a day.

Time: O(n), each index pushed and popped onceSpace: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[] dailyTemperatures(int[] temperatures) {
    int[] out = new int[temperatures.length];
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < temperatures.length; i++) {
        while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
            int day = stack.pop();
            out[day] = i - day;
        }
        stack.push(i);
    }
    return out;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.