Monotonic stack

A monotonic stack keeps its elements in sorted order—either strictly non-decreasing (often called “increasing”) or strictly non-increasing (“decreasing”) from bottom to top. When a new value would break that rule, you pop from the top until the rule holds again (or the stack empties). That discipline turns many “for every element, find the nearest …” problems into a single O(n) left-to-right scan. The same idea shows up in markets (next higher price, stock span), weather series, compilers, navigation search, and streaming analytics—see §4–§8 below after the C walkthrough.

On this page
  • Two flavors — increasing vs decreasing monotonic stacks
  • Why we pop — restore the invariant before pushing
  • Next greater to the right — classic interview pattern
  • Example in C — indices on the stack, one pass
  • Trace — first steps of the scan
  • Real domains — stocks, weather, compilers, navigation, systems design
  • Trade-offs — when the pattern shines vs what to watch for

1) Increasing vs decreasing

Which monotonic stack you keep (by the values at stored indices)
Variant Invariant (bottom → top) Typical use
Monotonic increasing Values never go down as you move toward the top. “Previous smaller,” some histogram tricks, counting visible elements.
Monotonic decreasing Values never go up as you move toward the top. Next greater to the right, “daily temperatures,” span problems.

This lesson implements next greater element to the right, which uses a strictly decreasing stack of indices (values fall as you go up the stack).

2) Scan rule (next greater to the right)

Walk i = 0 … n−1. The stack stores indices still waiting for their answer. Before pushing i, every index on top whose value is smaller than arr[i] has just found its next greater: it is arr[i].

Per-index work at position i
Step Meaning
Pop while … While the stack is not empty and arr[stack[top]] < arr[i], pop index j and set nge[j] = arr[i].
Push Push i. It waits for a later, larger element.
After the scan Any index still on the stack has no greater element to the right; store −1 (or another sentinel you choose).

Snapshot for arr[] = { 4, 5, 2, 25, … } — stack holds values at indices (bottom → top):

About to process index 3arr[3] = 25

After index 2

Values at stacked indices (decreasing upward)

5 2

Indices on the real stack are 1 then 2; values read 5 then 2.

After handling 25 at index 3

2 < 25 and 5 < 25 — both resolved

25

Pops assign nge[2]=25, nge[1]=25; then index 3 is pushed.

3) Example in C

The program fills nge[i] with the next strictly greater value to the right of arr[i], or −1 if none exists. The stack stores indices; compare through arr[stack[top]].

#include <stdio.h>

#define N 8

static int arr[N] = { 4, 5, 2, 25, 7, 2, 13, 12 };
static int nge[N];
static int stack[N];
static int top = -1;

// One left-to-right pass: decreasing stack of indices
static void next_greater_to_the_right(void) {
    int i;

    for (i = 0; i < N; i++)
        nge[i] = -1;

    for (i = 0; i < N; i++) {
        while (top >= 0 && arr[stack[top]] < arr[i]) {
            nge[stack[top]] = arr[i];
            top--;
        }
        stack[++top] = i;
    }
}

int main(void) {
    int i;

    next_greater_to_the_right();
    for (i = 0; i < N; i++)
        printf("%d -> %d\n", arr[i], nge[i]);
    return 0;
}

First lines of output: 4 -> 5, 5 -> 25, 2 -> 25, 25 -> -1, …

Trace (abbreviated)

Stack lists indices (values in parentheses). Pops happen only when the new arr[i] is strictly greater.

First four indices of the scan
i arr[i] Pops / assignments Stack (bottom → top)
0 4 0 (4)
1 5 nge[0]=5 1 (5)
2 2 1 (5), 2 (2)
3 25 nge[2]=25, nge[1]=25 3 (25)

4) Stock systems & trading

In trading and risk systems, daily (or intraday) prices form a sequence—exactly the kind of array monotonic stacks handle well. You often need next event or span answers for every day in one pass.

Questions monotonic stacks answer in stock-like time series
Question How it maps to the pattern
“When is the next day the stock price becomes higher than today?” Same family as next greater element to the right on a price array: each day waits on the stack until a higher closing price arrives.
“How many consecutive days before today had lower prices?” (Stock span) The classic stock span problem: a monotonic stack tracks prior days that are still “blocked” by smaller prices; pops resolve spans in O(n) total.
Where that helps in finance software
Use Role
Trend detection Spot when a new high “clears” many prior days in one scan—no repeated backward search for each day.
Algorithmic trading signals Feed indicators that depend on “first future breakout” or span counts over rolling windows.
Risk analysis systems Stress paths where you need how far back conditions held (span-style) under large histories.

Complexity: A naive approach that re-checks each past day for every i can be O(n²). A monotonic stack visits each index a bounded number of times—typically O(n) time and O(n) stack space for the whole series.

5) Weather forecasting & climate

Meteorological time series behave like stock curves: you ask when the next warmer (or colder) day arrives, or how long a cool spell lasts. The “daily temperatures” pattern is the same algorithmic core as next-greater on dates.

Typical questions (weather)
Question Idea
“When is the next warmer day?” Next greater on a temperature array (often with “days until” instead of the raw value).
“How long until temperature rises again?” Distance-to-next-warmer—same monotonic pass, different answer extraction.
Real applications
Area Examples
Consumer weather apps Products such as AccuWeather or The Weather Channel combine models and UI that surface “when it warms up” style outlooks over long forecasts.
Climate data analysis Batch pipelines that scan decades of readings for streaks and breakpoints.
Smart agriculture Planning frost risk or growing-degree windows from sequential station data.

6) Compiler design & expression parsing

Compilers walk structured text and numbers; “what is the nearest dominating operator or boundary?” often reduces to nearest smaller / greater style logic on a stream or tree—monotonic stacks keep candidates in order as the scan advances.

Monotonic stacks in compilation and parsing
Role Details
Operator precedence Shunting and shift–reduce parsers use stacks; monotonic variants help when you must resolve “which pending operator fires next” as precedence clarifies.
Nearest smaller / greater in syntax Useful in expression trees and token streams when building structure from left to right.
Where it shows up
System Notes
Compilers Production compilers (e.g. GCC) combine many techniques; stacks—including monotonic discipline in specific passes—support parsing and optimization steps.
Code parsing engines IDEs, linters, and language servers analyze source with stack-based state machines.
Expression evaluation Same stack family as postfix evaluation and infix conversion; monotonic refinements appear in harder interview and tool-chain variants.

7) Navigation & path optimization

When you sweep a route or a grid by cost or elevation, you often discard options that can never be optimal once a better frontier appears—LIFO with monotonic ordering is the right mental model for “drop dominated states.”

What you need in path-style problems
Need Stack angle
Next optimal path decision As you scan candidates, pop everything the new observation makes obsolete—keep only a monotonic chain of “still possible bests.”
Eliminating unnecessary paths dynamically Same pops: dominated partial paths never get revisited at linear cost per step.
Navigation, logistics, and games
Domain Examples
Navigation GPS and map pipelines that prune candidate segments when a shorter or faster link appears.
Route optimization Logistics and ride-sharing engines that score sequences in one sweep.
Games Pathfinding layers that evaluate moves with monotone cost envelopes (often combined with other structures).

8) Memory optimization & system design

At scale you want ordered views of a sliding stream without sorting the whole window every step. Monotonic stacks (or deques) maintain “only what can still matter” for the next insertions.

What monotonic stacks contribute
Goal Mechanism
Maintain ordered structure efficiently Keep a monotone chain of candidates; each new element may pop many, but each pushed item is removed at most once—linear total work.
Reduce redundant computation Avoid re-comparing every old entry when only the newest datum changes the winner.
Used in
Area Examples
Sliding window problems Min/max in every window—monotonic deque/stack patterns are standard.
Cache optimization Eviction or scoring policies that compare “freshness” along a timeline.
Real-time analytics Streaming dashboards that need extrema or “next breakout” over live metrics.

9) Trade-offs and practice

  • Pros — Linear time with a small stack; same skeleton for temperatures, largest rectangle, and “cart stock” style tasks.
  • Cons — You must pick the correct monotonic direction and tie-breaking (< vs <=) for each problem statement.

Related in this track: Stack applications · Postfix evaluation · Brackets validation.

Key takeaway

A monotonic stack is not a new ADT—it is a usage pattern: keep the stack ordered so the top always partners with the current scan line. Popping is how you finalize answers for older positions in one pass.

See also: Stack time complexity · Stack operations · Stack tutorial