Monotonic Stack

Daily Temperatures

Medium
Solve it on LeetCode ↗

The problem

For each day, how many days until a strictly warmer temperature? 0 if it never comes.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Push INDICES onto a stack whose temperatures are strictly decreasing top-to-bottom.
  2. 2For each new day i: while the stack top is colder than temps[i], pop it — its answer is i − poppedIndex.
  3. 3Push i.
  4. 4Whatever remains at the end never sees a warmer day → 0 (the default).

Key insight

Each index is pushed once and popped at most once — the two-nested-loops shape is deceptive; total work is O(n).

The solution

Watch out for

  • Store indices, not temperatures — the answer needs the distance.
  • "Strictly warmer": equal temperatures do NOT pop.