Pattern #10
Stack Parsing
RecommendedNested structures, expressions, paths, and collision simulation.
When to use
Input has nesting or must be reduced left-to-right with unmatched openers held for later.
Recognition cues
- Valid parentheses / decode string
- Basic calculator / RPN
- Asteroid collision / simplify path
Common pitfalls
- Wrong match map for brackets
- Not handling unary minus in calculators
- Mutating while iterating the stack incorrectly
90-second recognition drill
Which pattern fits best?
- Valid parentheses / decode string
- Basic calculator / RPN
- Asteroid collision / simplify path
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
(
0[
1{
2}
3]
4)
5stack
∅
Statestack=[]
How to think about it
A stack holds open work: unmatched brackets, partial numbers, path segments, or live asteroids. Closing tokens reduce the top until the structure is consistent. The final stack (or empty) is the answer.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Matching brackets | Push each opener. A closer pops the opener it maps to. Valid means every pop matches and the stack is empty | LC 20 |
| Path | .. pops. . and empty tokens are skipped. Any other token pushes. Join the survivors with one leading / |
LC 71 |
| RPN | A number pushes. An operator pops b then a and pushes a op b. Division truncates toward zero |
LC 150 |
| Calculator | A ( pushes the running total and the sign, then the inner sum restarts at 0. A ) applies the popped sign and adds that inner sum to the popped total |
LC 224 |
| Decode | A [ pushes the count and the prefix, then both reset. A ] repeats the current piece k times and appends it to the popped prefix |
LC 394 |
| Asteroids | A left-mover pops every smaller right-mover on top. Equal sizes destroy both. Push the new asteroid only when it survives | LC 735 |
Complexity baseline
Usually O(n) time and space in the depth or output size.
From template to problem
- Name the frame: an opener, a path segment, a value, a saved total plus sign, or a count plus prefix.
- Scan left to right. Each token either pushes or reduces the top.
- Pop order matters. RPN pops
bthena(LC 150). A calculator restarts the inner sum only after saving the outer total (LC 224). - The answer is an empty stack (LC 20), the last value (LC 150), or the survivors joined back into a string (LC 71, LC 394).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Stack Parsing · Template
/** Stack parsing template: valid parentheses. */
export function isValid(s: string): boolean {
const st: string[] = [];
const pair: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
for (const ch of s) {
if (ch === "(" || ch === "[" || ch === "{") st.push(ch);
else if (!st.length || st.pop() !== pair[ch]) return false;
}
return st.length === 0;
}
/** Stack parsing template: valid parentheses. */
export function isValid(s: string): boolean {
const st: string[] = [];
const pair: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
for (const ch of s) {
if (ch === "(" || ch === "[" || ch === "{") st.push(ch);
else if (!st.length || st.pop() !== pair[ch]) return false;
}
return st.length === 0;
}
#StatusProblemTypeDifficultyDone
- 1#20 Valid ParenthesesGuideeasy
- 2#71 Simplify PathGuidemedium
- 3#150 Evaluate Reverse Polish NotationGuidemedium
- 4#224 Basic CalculatorGuidehard
- 5#394 Decode StringGuidemedium
- 6#735 Asteroid CollisionGuidemedium