Courses / DSA Patterns for Working Engineers / Chapter 19
Module 6 · Matrices, stacks and graphs · Chapter 19 of 39
Stacks: Matching, Parsing and Nested Structure
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Graphs: Modelling, Breadth-First and Depth-First Search.
Part 1 · Introduction to stacks
Last in, first out
An undo button, a browser back button and the call stack of a running program all work the same way: the last thing added is the first thing taken back. That rule is a stack.
A stack holds items in order and allows two operations at one end: push adds an item on top, and pop removes and returns the top item. The top is always the most recent item that has not been removed. In JavaScript an array does the job, because push and pop work at its end in constant time. To look at the top without removing it, write stack[stack.length - 1] or stack.at(-1). pop on an empty array returns undefined and does not fail, so check stack.length first when an empty stack would be a mistake.
A stack fits any problem with nested structure: brackets inside brackets, a call inside a call, a folder inside a folder. In each, the thing that closes next is the most recent thing still open. When you meet that shape, ask what the stack should hold. The answer is whatever is still waiting to be finished.
This chapter uses a stack for matching, for evaluating formulas, for decoding nested labels, for timing nested calls and for cleaning paths. Questions about finding the next greater value or maintaining sorted order on a stack belong to the monotonic stack chapter and are not taught here.