Daily Temperatures

Medium Monotonic StackArray

Problem

Given an array temps of daily temperatures, return an array answer where answer[i] is the number of days you have to wait until a warmer temperature. If no future day is warmer, put 0.

Example 1 Input: temps = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0]
Example 2 Input: temps = [30,40,50,60] Output: [1,1,1,0]
Example 3 Input: temps = [30,60,90] Output: [1,1,0]

Constraints

Approach — Monotonic Stack

This is a Monotonic Stack problem. The idea: scan once and keep a stack whose order stays meaningful, popping elements as soon as a later value resolves them. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def dailyTemperatures(self, temps):
        res = [0] * len(temps)
        st = []
        for i, t in enumerate(temps):
            while st and temps[st[-1]] < t:
                j = st.pop()
                res[j] = i - j
            st.append(i)
        return res

Java

import java.util.ArrayDeque;
import java.util.Deque;

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Daily Temperatures interactively → ← All solutions