Daily Temperatures

MediumMonotonic Stack🧩 Monotonic StackLeetCode #739 ↗Updated

Problem

You get the daily temperatures as an array temperatures. For every day i, report how many days you must wait until a strictly warmer day arrives. If no warmer day ever comes, report 0 for that day.
Input[73,74,75,71,69,72,76,73]Output[1,1,4,2,1,1,0,0]
Input[30,40,50,60]Output[1,1,1,0]
Input[30,60,90]Output[1,1,0]

1 ≤ n ≤ 105  ·  30 ≤ temperatures[i] ≤ 100

Try it yourself

Java
class Solution {
    public int[] dailyTemperatures(int[] T) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
This is “next greater element”. Keep a stack of days still waiting for a warmer day; their temperatures are decreasing, so a new warm day resolves waiting days from the top of the stack until it meets one at least as warm.
PatternMonotonic Stack

Instinct Each element needs its nearest bigger or smaller neighbour (next warmer day, span, widest bar) - keep a sorted stack of waiting indices.

Memory hack Tall people block the view - a newcomer kicks out everyone shorter waiting behind, and each kicked-out person just found their answer.

Open the Monotonic Stack guide →

Approaches

Brute ForceScan Forward from Every Day

Time O(n2)Space O(1) extra

For each day i, walk j = i+1, i+2, ... and stop at the first T[j] > T[i]; the answer is j - i. A strictly decreasing input forces every scan to run to the end.

Java
public int[] dailyTemperatures(int[] T) {
    int n = T.length;
    int[] result = new int[n];
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (T[j] > T[i]) {
                result[i] = j - i;
                break;
            }
        }
    }
    return result;
}

Trivially correct, but ~5·109 steps for n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceScan Forward from Every DayO(n2)O(1) extra
BetterBackward Scan + Next-Index per TemperatureO(n · W)O(W)
OptimalMonotonic Decreasing Stack of IndicesO(n)O(n)
Common pitfalls
  • Pushing temperatures instead of indices — you need positions to compute distances.
  • Using >= in the pop condition — equal temperature is not warmer.
  • Using java.util.Stack (synchronized, slower) instead of ArrayDeque.
Interview tips
  • Name the pattern out loud: “next greater element → monotonic stack”.
  • Argue O(n) by amortisation: every index is pushed once and popped at most once.
  • Mention that leftover stack entries default to 0 — no extra pass needed.
Pattern
Monotonic stack → for each element, find the nearest greater/smaller element to its left or right.
My notes saved in this browser