Valid Parentheses
Master this topic with zero to advance depth.
Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Visual Representation
s = "{ [ ] }"
Step 1: '{' -> Push to Stack. Stack: ['{']
Step 2: '[' -> Push to Stack. Stack: ['{', '[']
Step 3: ']' -> Matches Top '['. Pop. Stack: ['{']
Step 4: '}' -> Matches Top '{'. Pop. Stack: []
Result: Valid (Stack is Empty)Examples
Level I: Brute Force (String Replace)
Intuition
Regular expressions or string replacements can continuously remove valid adjacent pairs (), {}, [] until the string is empty or no more replacements can be made.
Level II: Recursive (Function Call Stack)
Intuition
Instead of an explicit stack object, we can use recursion. Each function call 'expects' a specific closing bracket. If it finds one, it returns; if it finds another opening bracket, it recurses. This demonstrates how the computer's memory uses a stack internally.
Level III: Optimal (Stack Mapping)
Intuition
Iterate through the string. If we see an opening bracket, push its corresponding closing bracket onto the stack. If we see a closing bracket, check if it matches the top of the stack. This simplifies the logic by storing what we expect next.
Detailed Dry Run
| Char | Action | Stack Status | Match? |
|---|---|---|---|
| '(' | Push ')' | [')'] | - |
| '[' | Push ']' | [')', ']'] | - |
| ']' | Pop | [')'] | Yes |
| ')' | Pop | [] | Yes |
⚠️ Common Pitfalls & Tips
Be careful with strings that only contain opening brackets, or strings where the stack becomes empty too early.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.