AlgoTales · Roadmap

Monotonic stack

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A monotonic stack is a stack that is kept always in order, for example from big to small, by removing items that can never matter again before adding a new one. It answers questions about the nearest bigger or smaller neighbour in one pass.

Practical use cases

  • Web app: Days until a higher price. A price-tracking page lists daily prices and, for each day, shows how many days passed until the price was higher. Comparing each day with every later day is slow for years of data. A monotonic stack keeps only days still waiting for a higher price, so one pass gives every answer.
  • Web app: Highlighting the nearest higher score in a table. A student results page lets teachers see, for each student, who is the next one in the roll list with a better score. The stack holds only students still waiting for someone better. A newcomer settles all waiting students below them at once.
  • System: Charting libraries and parsers. Charting libraries that work out which bars are visible behind taller ones, and some parsers that match items to their enclosing block, rely on this pattern. It replaces a slow nested comparison with a single sweep over the data, which matters when a chart has tens of thousands of points.

The story: The Photo Day Rule

On School Photo Day, Mrs. Sharma lined the class up on risers. Her rule: the tallest at the back and shorter ones in front, so every face can be seen. Students kept arriving one by one and joining the line from the right end.

When a new student arrived, Mrs. Sharma checked the last child in line. If that child was shorter or the same, the little one was hidden behind the newcomer anyway, so she sent them away from the line. She kept checking the next child, and the next, until she found someone taller, or the line ended. Only then did the newcomer join.

Kabir noticed something clever: the line was always in order, tall to short, and every child was removed at most once. He had spotted a monotonic stack: a stack where, before each push, you pop everything that would break the order.

The popped children are not wasted either. At the moment someone is popped, you learn something useful: "a taller person has just arrived!" Many classic problems are solved by exactly that moment. The next few lessons use it to find the next greater element, stock spans, and the biggest rectangle in a histogram.

How to spot this problem, and where you need it

For each item in a list you want the nearest item before or after it that is bigger or smaller, and checking every other item for each one is far too slow.

Signs you need it

  • The task says "next greater", "next smaller", "nearest higher", "first value that exceeds" or "how many days until".
  • Your code has a loop inside a loop that scans forward or backward from each item until it finds a bigger or smaller one.
  • Data is a time series of prices, temperatures or scores, and every point needs a comparison with later or earlier points.

Where to use it in a project

  • Price, temperature and traffic dashboards showing waiting time until a higher or lower value.
  • Chart code that needs the nearest taller bar on either side.
  • Parsers and layout code that match items to their nearest larger enclosing item.

The solution

Walk through the list once with a stack that stays in order (for example decreasing). For each new item, pop every item on the stack that is smaller; for each popped item, the new item is the answer you were looking for. Then push the new item. Items stay on the stack only while still waiting for their answer, and each item is pushed and popped at most once.

Payoff: Before: comparing each of 100,000 days with all later days. After: about 200,000 pushes and pops, and the dashboard loads instantly.

Explain it like I am 8

Line up kids from tallest to shortest. When a taller kid walks in, every shorter kid at the end of the line goes away, because they would be hidden anyway. Then the new kid joins. The line is always neat from tall to short.

How it works, step by step

  1. Choose the order the stack must keep: decreasing (big at the bottom) or increasing (small at the bottom).
  2. For each new item, look at the top of the stack.
  3. While the top breaks the order (for a decreasing stack: top ≤ new item), pop it. Use the pop moment to record whatever the problem needs.
  4. Push the new item. The stack is in order again.
  5. Every item is pushed once and popped at most once, so the whole walk costs only one pass.

The code in four languages

PHP

<?php
// Keep a stack that is strictly decreasing from bottom to top.
function monotonicDecreasing(array $nums): array {
    $stack = [];
    foreach ($nums as $x) {
        // pop everything that is not bigger than the newcomer
        while ($stack && end($stack) <= $x) {
            array_pop($stack);
        }
        $stack[] = $x;                               // now the order is safe again
        echo 'after ' . $x . ': ' . implode(',', $stack) . PHP_EOL;
    }
    return $stack;
}

$left = monotonicDecreasing([4, 2, 7, 3, 5, 1]);
echo 'survivors: ' . implode(',', $left) . PHP_EOL;  // 7,5,1

JavaScript

// Keep a stack that is strictly decreasing from bottom to top.
function monotonicDecreasing(nums) {
  const stack = [];
  for (const x of nums) {
    // pop everything that is not bigger than the newcomer
    while (stack.length && stack[stack.length - 1] <= x) {
      stack.pop();
    }
    stack.push(x);                                   // now the order is safe again
    console.log('after ' + x + ': ' + stack.join(','));
  }
  return stack;
}

const left = monotonicDecreasing([4, 2, 7, 3, 5, 1]);
console.log('survivors: ' + left.join(','));         // 7,5,1

Java

import java.util.*;

public class Main {
    // Keep a stack that is strictly decreasing from bottom to top.
    static List<Integer> monotonicDecreasing(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int x : nums) {
            // pop everything that is not bigger than the newcomer
            while (!stack.isEmpty() && stack.peek() <= x) {
                stack.pop();
            }
            stack.push(x);                               // now the order is safe again
            System.out.println("after " + x + ": " + join(stack));
        }
        return bottomToTop(stack);
    }

    // ArrayDeque used as a stack iterates top-first, so flip it for printing.
    static List<Integer> bottomToTop(Deque<Integer> stack) {
        List<Integer> list = new ArrayList<>(stack);
        Collections.reverse(list);
        return list;
    }

    static String join(Deque<Integer> stack) {
        StringJoiner sj = new StringJoiner(",");
        for (int v : bottomToTop(stack)) sj.add(String.valueOf(v));
        return sj.toString();
    }

    public static void main(String[] args) {
        List<Integer> left = monotonicDecreasing(new int[]{4, 2, 7, 3, 5, 1});
        StringJoiner sj = new StringJoiner(",");
        for (int v : left) sj.add(String.valueOf(v));
        System.out.println("survivors: " + sj);          // 7,5,1
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func join(nums []int) string {
	parts := make([]string, len(nums))
	for i, v := range nums {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ",")
}

// monotonicDecreasing keeps a stack that is strictly decreasing from bottom to top.
func monotonicDecreasing(nums []int) []int {
	var stack []int
	for _, x := range nums {
		// pop everything that is not bigger than the newcomer
		for len(stack) > 0 && stack[len(stack)-1] <= x {
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, x) // now the order is safe again
		fmt.Println("after " + strconv.Itoa(x) + ": " + join(stack))
	}
	return stack
}

func main() {
	left := monotonicDecreasing([]int{4, 2, 7, 3, 5, 1})
	fmt.Println("survivors: " + join(left)) // 7,5,1
}

Time: O(n) · Extra space: O(n). Even with a loop inside a loop, each item is pushed once and popped once, so the total work is a few steps per item.

Watch out for

  • Thinking the inner while loop makes it O(n²). It cannot: an item can be popped only once, so the pops add up to at most n over the whole run.
  • Mixing up strict and non-strict comparison (< versus <=). It decides what happens with equal values, so choose deliberately.
  • Storing values when the problem needs positions. Often you must push indexes and look up the values.

Quick check

  1. In a decreasing monotonic stack, what do you do when a bigger number arrives?
    • Pop smaller or equal tops, then push it
    • Clear the whole stack
    • Push it on top directly
  2. Is the monotonic stack walk O(n) or O(n²)?
    • O(n²), because of the while loop
    • O(n), because each item is popped at most once
    • O(log n)
  3. Which numbers does the stack hold after walking 4, 2, 7, 3, 5, 1?
    • 7, 3, 1
    • 4, 2, 1
    • 7, 5, 1