CodingNodes / Stack / Valid Parentheses System design Space play · ←→ step · R restart

Problem

You get a string s made only of the bracket characters ( ) [ ] { }. Decide whether the brackets are balanced.

Balanced means three things: every opening bracket is closed by a bracket of the same kind, brackets close in the reverse order they were opened (no crossing), and no closing bracket appears without an open one waiting for it.

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s contains only ( ) [ ] { }

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each character is read once and causes at most one push or one pop, both O(1).

Space: In the worst case (all openers) every character is pushed, so the stack holds up to n entries.

Push every opening bracket. When a closing bracket arrives, the most recent unclosed opener must be its partner, and that is exactly the top of the stack. Pop on a match, fail on a mismatch or an empty stack. At the end the stack must be empty.