Chapter 07 - Stacks

Last in, first out. A stack remembers what we must come back to, in reverse order.

Coding Interview Patterns book cover with the Rust logo and a CHAP 07 label, the chapter on stacks

This page is the entry point of chapter 7 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

A stack is the right tool when the most recent pending item is the next one to handle: an opening bracket waiting for its closing one, an operand waiting for its operator. A monotonic stack, whose values stay sorted, finds the next larger element of every item in a single pass, in \(O(n)\) instead of \(O(n^2)\).

When to reach for it

  • Nested structures and matching pairs: parentheses, tags, expressions.
  • “Next larger” or “next smaller” element questions.
  • Repeated removal of adjacent items, undo operations, or a queue built from two stacks.

In Rust

  • A Vec is the stack: push, pop and last. pop returns an Option, so an unbalanced expression shows up as None, not as a crash.
  • For a double-ended queue (maximums of a sliding window), use std::collections::VecDeque.
  • Store indexes rather than values in a monotonic stack: the value is one lookup away, the position is not.

Problems in this chapter

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude