← Back to Blog

Next Warmer Day Alert - Solving in O(n) with a Monotonic Stack - AlgoNote

Monotonic StackStackData StructureCoding TestAlgoNote

"Can I wear short sleeves tomorrow?"

Suppose you're building a weather app. What users want to know is surprisingly simple: "When will a day hotter than today come?"

Given the forecast for the next few days, for each day you want to report how many days later the first warmer day is. If no warmer day ever comes, the answer is 0.

Example: for temperatures [23, 24, 22, 21, 25, 28, 26], the answer is [1, 3, 2, 1, 1, 0, 0].

Day 1 (24°) first gets warmer 3 days later at Day 4 (25°); Day 5 (28°) has no warmer day after it, so 0.


The first solution that comes to mind (and its limit)

Intuitively, you'd do this: for each day, scan to the right until you find a warmer day.

for each day i:
    for j = i+1 .. end:
        if temps[j] > temps[i]: answer = j - i; break

This works on small inputs. But with 100,000 days? 100k × 100k = 10 billion comparisons → time limit exceeded. The O(n²) of a double loop trips people up constantly in coding tests.


Why a stack? — "Days that wait"

Let's flip our thinking. Picture each day as a "customer waiting for an answer."

  • Day 0 (23°): "When will it get hotter than me?" → Unknown yet. Gets in line (the stack) to wait.
  • Day 1 (24°) appears: 24 > 23! Day 0's answer is found immediately (1 day later) → Day 0 leaves the line.
  • Day 2 (22°), Day 3 (21°): it keeps getting colder, so nobody finds an answer and the line grows.
  • Day 4 (25°) appears: 25 overtakes the waiting 21 → 22 → 24 nearest-first, all at once! Three of them find their answers and leave together.

Notice it? The most recently queued leaves first. That is exactly how a stack (LIFO) behaves.

And if you look at the temperatures still in line, they're always decreasing (24 → 22 → 21). A stack that maintains this *monotonicity* is called a Monotonic Stack.


The key: "push once, pop at most once"

The reason the monotonic stack is fast is crisp.

  • Each day is pushed exactly once,
  • and when it meets a warmer day, it is popped at most once.

So the total operation count never exceeds 2n — i.e. O(n). The double loop's 10 billion operations shrink to about 100,000.

This pattern shows up in countless disguises: "next greater element", "nearest one to the right", "right before the stock drops". Learn the principle once, and problems wearing different clothes start to look identical.


See it with your own eyes

We built the entire process as a step-by-step visualization: temperature bars lined up, days without an answer piling onto the stack, and the moment a hotter day appears triggering a cascade of pops that fill in the answers. You'll see the stack change and the answer array fill in, all at a glance.

👉 Next Warmer Day Alert — watch the step-by-step visualization

Next Warmer Day Alert - Solving in O(n) with a Monotonic Stack - AlgoNote - AlgoNote | 알고노트(AlgoNote)