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
1/8

Matching brackets: stack holds unmatched openers.

(
0
[
1
{
2
}
3
]
4
)
5
stack
∅
Statestack=[]
Key:CurrentActive rangeMatchSettled

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

  1. Name the frame: an opener, a path segment, a value, a saved total plus sign, or a count plus prefix.
  2. Scan left to right. Each token either pushes or reduces the top.
  3. Pop order matters. RPN pops b then a (LC 150). A calculator restarts the inner sum only after saving the outer total (LC 224).
  4. 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;
}
#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