Stacks, Queues & Heaps
Stack
🍽️
Picture this
A towering stack of porcelain plates on the cellar stairs — you can only ever touch the top one.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
matchingvalid parenthesesnestedundolast seenbalanced
Ask yourself
- Matching / nesting (brackets, tags)?
- Need the most-recent unmatched thing?
- Evaluate or simplify left-to-right with backtracking of one step?
Canonical template
const stack: string[] = [];
for (const ch of s) {
if (opens.has(ch)) stack.push(ch);
else if (!stack.length || stack.pop() !== match[ch]) return false;
}
return stack.length === 0;
Common pitfalls
Popping an empty stack.
Forgetting the stack must be empty at the end.