Chapter 07 - Stacks
Last in, first out. A stack remembers what we must come back to, in reverse order.
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
Vecis the stack:push,popandlast.popreturns anOption, so an unbalanced expression shows up asNone, 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
- p130 - Valid Parenthesis Expression: Valid Parenthesis Expression (Stacks) solved in Rust: determine whether a string made of (, ), [, ], { and } is well formed.
- p132 - Next Largest Number to the Right: Next Largest Number to the Right (Stacks) solved in Rust: for each number in an array, find the first larger number to its right.
- p137 - Evaluate Expression: Evaluate Expression (Stacks), solved in Rust. Given a string representing expression. Evaluate & return the value. May contain int, parentheses, addition and…
- bonus064 - Repeated Removal of Adjacent Duplicates: Repeated Removal of Adjacent Duplicates (Stacks), solved in Rust. Given a string, continually perform the following operation: Remove pairs of adjacent…
- bonus067 - Implement a Queue Using Stacks: Implement a Queue Using Stacks (Stacks), solved in Rust. Implement a queue using the stack data structure. Include the following functions:
- bonus073 - Maximums of Sliding Window: Maximums of Sliding Window (Stacks), solved in Rust. A sliding window of size k slides through an integer array from left to right. Create a new array that…
Other chapters
All the chapters, with every problem, are listed on the series page.