Practice Discrete Math

Algorithms / Stack Balanced Delimiters

Least You Need to Know: Stacks, Balanced Delimiters, and Most-Recent Openings

Balanced-parentheses problems are stack problems because each closing bracket must match the **most recent unmatched opening**. That last-opened, first-closed behavior is exactly LIFO order.

The least you need to know

Key notation

push place an opening symbol on the top of the stack
pop remove the most recent unmatched opening
top the current most recent unmatched opening

Tiny worked example

  • Scan left to right.
  • Push each opening bracket.
  • For each closing bracket, the stack top must hold the matching opening bracket; then pop it.
  • The string is balanced exactly when no mismatch appears and the stack ends empty.

Common mistakes

How to recognize this kind of problem

Start practice