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
- Read the brackets left to right with a stack.
- An opening bracket is pushed onto the stack.
- 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.
- At the end the stack must be empty (nothing left open).
Watch it run
Loading animation…