Skip to content
StackDecode
Stacks & queuesAnimated

Valid Parentheses

Push openers, pop on closers, and check they match.

Time

O(n)

Extra space

O(n)

Use it for

Balanced brackets in code and expressions.

How it works

  1. Read the brackets left to right with a stack.
  2. An opening bracket is pushed onto the stack.
  3. A closing bracket must match the bracket on top of the stack: pop it. If the stack is empty or the types differ, the string is invalid.
  4. At the end the stack must be empty (nothing left open).

Watch it run

Loading animation…