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
(
[
{
}
]
)
stack
∅
Matching brackets: stack holds unmatched openers.
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 | Notes |
|---|---|---|
| Matching | Push open; pop on close | Empty ⇒ valid |
| Nested decode | Push count and string | Expand on ‘]’ |
| Collisions | Pop while top loses | Push survivor |
Complexity baseline
Usually O(n) time and space in the depth or output size.
From template to problem
- Define what a stack frame stores (char, number, string builder, direction).
- Scan left to right; on each token either push or reduce.
- Handle edge cases (empty, single token, leading signs).
- Serialize the remaining stack into the result.
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