Stack: Stacks and monotonic stacks
Goal: Learn the pattern first, then apply it to the 8 roadmap problems in this chapter.
When this pattern appears
The newest unresolved item depends on a later item, nested structure, or last-in-first-out evaluation.
The reusable idea
Store indices when answers depend on distance. State what every stack entry is waiting for.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What does an item remaining on the stack mean? When is it safe to resolve it?
Common failure modes
Operand order, strict versus non-strict comparisons, sentinel flushing, and unmatched items.
Chapter problems from the workbook
- #23 · Valid Parentheses — Day 13, Easy. Open problem ↗
- #24 · Implement Queue using Stacks — Day 13, Easy. Open problem ↗
- #25 · Min Stack — Day 13, Medium. Open problem ↗
- #26 · Evaluate Reverse Polish Notation — Day 15, Medium. Open problem ↗
- #27 · Daily Temperatures — Day 15, Medium. Open problem ↗
- #28 · Generate Parentheses — Day 16, Medium. Open problem ↗
- #29 · Car Fleet — Day 16, Medium. Open problem ↗
- #30 · Largest Rectangle in Histogram — Day 17, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.