Daily temperatures

For each day, find how many days until a warmer one, using a monotonic stack of days still waiting for an answer.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

The stack holds days whose warmer day has not been found yet, with temperatures decreasing from bottom to top. When a warmer day arrives, it is the answer for every cooler day still waiting on top of the stack.

Code

public static int[] DailyTemperatures(int[] temps) {
    var result = new int[temps.Length];
    var stack = new Stack<int>(); // indices waiting for a warmer day
    for (int i = 0; i < temps.Length; i++) {
        while (stack.Count > 0 && temps[stack.Peek()] < temps[i]) {
            int j = stack.Pop();
            result[j] = i - j;
        }
        stack.Push(i);
    }
    return result;
}
static int[] dailyTemperatures(int[] temps) {
    int[] result = new int[temps.length];
    Deque<Integer> stack = new ArrayDeque<>(); // indices waiting for a warmer day
    for (int i = 0; i < temps.length; i++) {
        while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
            int j = stack.pop();
            result[j] = i - j;
        }
        stack.push(i);
    }
    return result;
}
vector<int> dailyTemperatures(const vector<int>& temps) {
    vector<int> result(temps.size(), 0);
    stack<int> st; // indices waiting for a warmer day
    for (int i = 0; i < (int)temps.size(); i++) {
        while (!st.empty() && temps[st.top()] < temps[i]) {
            int j = st.top(); st.pop();
            result[j] = i - j;
        }
        st.push(i);
    }
    return result;
}
def daily_temperatures(temps: list[int]) -> list[int]:
    result = [0] * len(temps)
    stack = []  # indices waiting for a warmer day
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            result[j] = i - j
        stack.append(i)
    return result

Tips

In the .NET library

Every index is pushed once and popped at most once, so the while loop total work across the whole run is still O(n), even though it looks nested.