Pattern 3 of 18 · Foundations

Stack

LIFO order for matching, backtracking through history, and monotonic tricks.

A stack is last-in-first-out — the most recently added item is the first one removed. It's the natural fit whenever "the most recent unmatched thing" matters, like nested brackets or undo history.

Key concepts

  • Push/pop operations run in O(1).
  • Matching pairs: push opening symbols, pop and compare on closing symbols.
  • Monotonic stack: keep the stack's elements in increasing or decreasing order, popping whenever a new element would break that order — used for "next greater/smaller element" problems.

When to use it

  • You're validating nested or paired structures (parentheses, tags, nested expressions).
  • You need to track "the most recent X that hasn't been resolved yet."
  • You're looking for the next larger or smaller element relative to each position.

Tips

  • If a problem mentions "nested" or "matching pairs," a stack is almost always the answer.
  • For monotonic-stack problems, decide up front whether you want an increasing or decreasing stack — it depends on whether you need the next greater or next smaller value.
  • An empty stack at the end (or a leftover unmatched item) is usually your validity check.

Practice problems (7)

Blind 75 (1):

More from Blind 150 (6):

See the full roadmap →