AlgoTales · Roadmap

Monotonic stack

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

Where you will meet this in real life

A monotonic stack is a pile where items are kept in a steady order (always bigger toward the bottom, say). When a new item breaks the order, you pop the items it beats and give them their answer. It finds "next bigger" or "next smaller" for everything in one pass.

Practical use cases

  • Web app: Days until a higher stock price. A finance page shows, for each day, how many days until the price was higher. Looking ahead from every day is slow. A stack of waiting days is resolved the moment a higher price shows up, so one pass gives every answer.
  • Web app: Weather widget: wait for a warmer day. A weather app answers "how many days until it is warmer than today?" for the whole forecast. A stack of still-waiting days is resolved as each warmer day arrives, so one pass fills in every answer.
  • Web app: Histogram or skyline chart sizing. A chart component needs the largest rectangle that fits under bars. The stack finds, for each bar, the nearest shorter bars on both sides in one pass. Each bar is looked at only a couple of times, so even a chart with thousands of bars is sized quickly.
  • System: Expression parsers and rain water trapped. Compilers use stacks to handle nested brackets and operators, and trapped-rain-water puzzles use the same pile idea. A long expression is read once, while the stack keeps track of what is still waiting for its match.

The story: Waiting for a Warmer Day

It was winter in Delhi, and Mira kept a diary of each morning's temperature: 73, 74, 75, 71, 69, 72, 76, 73 (in the old units her grandfather liked). Grandpa Bhaskar asked, "On each day, how many days did you have to wait for a warmer day?" Day 0 waited 1 day (74). Day 2 waited 4 days (until 76).

Kabir tried: for each day, look ahead until something warmer appears. For long winters that is a lot of looking ahead, again and again over the same days. Mira found the smell in the sentence: "next greater element", "next warmer", "first bigger to the right". That means a monotonic stack.

Her trick: keep a stack of days that are still waiting for a warmer day. When a new day arrives, it is the answer for every waiting day that is cooler than it, so pop them and tell them how long they waited. Then the new day stands in line. The waiting stack always holds temperatures that go down from bottom to top: monotonic.

Each day is pushed once and popped at most once, so the whole winter takes a single pass.

How to spot this problem, and where you need it

For each item in a list, you want the next item that is bigger or smaller, or how far away it is, and looking ahead from every item makes the page slow.

Signs you need it

  • The wording is "next greater", "next smaller", "days until warmer", "stock span" or "largest rectangle".
  • You have a loop within a loop: for each item, scan forward until something bigger appears.
  • Items seem to be waiting for something that will resolve many of them at the same time.

Where to use it in a project

  • Price, weather and metrics screens that show how long until a value rises or falls.
  • Chart and layout calculations that depend on neighbouring bars or boxes.
  • Parsers that match nested brackets and operators when reading expressions.

The solution

Go through the list once with an empty stack that holds items still waiting for an answer. For each new item, while the item at the top of the stack is smaller, pop it and record that the new item is its answer. Then push the new item. Anything left at the end has no answer. Every item is pushed once and popped once.

Payoff: Before: 10,000 days times up to 10,000 look-aheads. After: about 20,000 stack moves.

Explain it like I am 8

Kids stand in a line facing the front and each wants to know who is the first taller kid behind them. A new taller kid arrives and tells every shorter kid waiting: "I am your answer!" Those kids sit down. Only kids still waiting stay standing.

How it works, step by step

  1. Clues: "next greater/smaller element", "nearest bigger to the right/left", "how many days until warmer", "span", "histogram". Think monotonic stack.
  2. Keep a stack of indexes that are still waiting for their answer, kept in order so values only go one way.
  3. For each new element, while the stack is not empty and the element at the top is smaller than the new one: pop it. The new element is its answer (i - top days).
  4. Push the new index. It now waits for something bigger.
  5. When the loop ends, whatever is left never found a bigger element: its answer is 0 (or "none").

The code in four languages

PHP

<?php
// Daily Temperatures: for each day, days until a warmer day (0 if never)
function dailyTemperatures(array $temps): array {
    $n = count($temps);
    $answer = array_fill(0, $n, 0);
    $stack = [];                                   // indexes still waiting
    for ($i = 0; $i < $n; $i++) {
        // Today is warmer than the day on top: that day gets its answer.
        while (!empty($stack) && $temps[end($stack)] < $temps[$i]) {
            $j = array_pop($stack);
            $answer[$j] = $i - $j;
        }
        $stack[] = $i;                             // today now waits too
    }
    return $answer;
}
echo implode(", ", dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]));
// 1, 1, 4, 2, 1, 1, 0, 0

JavaScript

// Daily Temperatures: for each day, days until a warmer day (0 if never)
function dailyTemperatures(temps) {
  const n = temps.length;
  const answer = new Array(n).fill(0);
  const stack = [];                                // indexes still waiting
  for (let i = 0; i < n; i++) {
    // Today is warmer than the day on top: that day gets its answer.
    while (stack.length && temps[stack[stack.length - 1]] < temps[i]) {
      const j = stack.pop();
      answer[j] = i - j;
    }
    stack.push(i);                                 // today now waits too
  }
  return answer;
}
console.log(dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]).join(", "));
// 1, 1, 4, 2, 1, 1, 0, 0

Java

import java.util.*;

public class Main {
    // Daily Temperatures: for each day, days until a warmer day (0 if never)
    static int[] dailyTemperatures(int[] temps) {
        int n = temps.length;
        int[] answer = new int[n];
        Deque<Integer> stack = new ArrayDeque<>();       // indexes still waiting
        for (int i = 0; i < n; i++) {
            // Today is warmer than the day on top: that day gets its answer.
            while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
                int j = stack.pop();
                answer[j] = i - j;
            }
            stack.push(i);                               // today now waits too
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72, 76, 73})));
        // [1, 1, 4, 2, 1, 1, 0, 0]
    }
}

Go

package main

import "fmt"

// dailyTemperatures: for each day, days until a warmer day (0 if never).
func dailyTemperatures(temps []int) []int {
	n := len(temps)
	answer := make([]int, n)
	var stack []int // indexes still waiting
	for i := 0; i < n; i++ {
		// Today is warmer than the day on top: that day gets its answer.
		for len(stack) > 0 && temps[stack[len(stack)-1]] < temps[i] {
			j := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			answer[j] = i - j
		}
		stack = append(stack, i) // today now waits too
	}
	return answer
}

func main() {
	fmt.Println(dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}))
	// [1 1 4 2 1 1 0 0]
}

Time: O(n) · Extra space: O(n). Every index is pushed once and popped at most once, even though there is a loop inside a loop.

Watch out for

  • Storing the values instead of the indexes. You need positions to compute how long a day waited.
  • Thinking the inner while makes it O(n²). Total pops can never exceed total pushes.
  • Using <= vs < carelessly: "strictly warmer" needs <; equal temperatures should keep waiting.

Quick check

  1. Which phrase is the monotonic-stack smell?
    • "Number of ways to climb stairs"
    • "Shortest path in a grid"
    • "Next greater element to the right"
  2. When a new day is warmer than the day on top of the stack?
    • Push it on top
    • Pop the top day, its answer is found
    • Clear the whole array
  3. Why is it O(n) with a loop inside a loop?
    • The inner loop runs only twice
    • The array is sorted
    • Each index is pushed once and popped at most once