Command Palette

Search for a command to run...

Module 9

Stack and Monotonic Stack

Last in, first out: match brackets, undo, evaluate expressions, and find the next greater element for every item in one pass.

Intermediate 3 lessons 8 problems ~40 min of lessons

A stack only lets you touch its top. That restriction is exactly what nested structures need: the most recently opened bracket must close first, the most recent action is undone first, and the innermost expression is evaluated first.

The second half of the module covers the monotonic stack, a stack kept in sorted order. It answers "what is the next greater (or smaller) element?" for every position in O(n), and it's the key to problems like Daily Temperatures and Largest Rectangle in Histogram.

Best after: Arrays

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The canonical stack problem: the most recent opener must close first.

  2. Store extra state with each element (the minimum so far) so every query stays O(1).

  3. Postfix expressions need no brackets: push numbers, and each operator pops its two operands.

  4. Stacks of saved state: on '[' save what you've built and the repeat count; on ']' pop and combine.

  5. The monotonic stack with distances: each warmer day pops every cooler day waiting on the stack.

  6. Compute next-greater answers for one array with a monotonic stack, then look them up for another with a hash map.

  7. Sort by position, then compare arrival times from the front: a car that would arrive sooner than the fleet ahead joins it.

  8. For each bar, the widest rectangle at its height spans to the nearest shorter bar on each side, found with an increasing stack.