Skip to content
ΣDSA Patterns
Menu
Language

Pattern #10

Stack Parsing

Recommended

Nested 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

  1. Define what a stack frame stores (char, number, string builder, direction).
  2. Scan left to right; on each token either push or reduce.
  3. Handle edge cases (empty, single token, leading signs).
  4. 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;
}
#StatusProblemTypeDone
  1. 1#20 Valid ParenthesesGuide
  2. 2#71 Simplify PathGuide
  3. 3#150 Evaluate Reverse Polish NotationGuide
  4. 4#224 Basic CalculatorGuide
  5. 5#394 Decode StringGuide
  6. 6#735 Asteroid CollisionGuide