Daily Temperatures

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given a list of daily temperatures, return for each day how many days you must wait for a strictly warmer day. If no warmer day comes later, the answer for that day is 0.

    The cleanest introduction to the monotonic stack, the tool for every "next greater element" question: next higher price, next taller building, next larger number. Original problem: LeetCode 739.

    Example

    Each arrow points to the first later day that is warmer; days with no arrow get 0.
    Each arrow points to the first later day that is warmer; days with no arrow get 0.
    Input:  [14, 12, 15, 11, 13, 18, 16]
    Output: [2, 1, 3, 1, 1, 0, 0]
    Input:  [5, 5, 6]
    Output: [2, 1, 0]        # an equal temperature is not warmer

    Constraints (assumed)

    • 1 ≤ n ≤ 10⁵ days.
    • Temperatures are integers in a small range (say 30 to 100 in Fahrenheit).

    What this question tests

    • Recognising a "next greater element" question and reaching for a monotonic stack.
    • The amortised argument: each index is pushed and popped at most once, so the nested loop is still O(n).
    • Storing indices, not values, so you can compute distances.

    Questions to ask first

    1. Does an equal temperature count as warmer? (Here: no, strictly warmer.)
    2. What if no warmer day exists? (Here: 0.)
    3. How large is n? O(n²) is fine for 100 days, not for 10⁵.
    4. What is the temperature range? A small range allows a different O(n · range) trick.