Browse Curriculum
FAANGPrep Sprint
Easy
Valid Parentheses
Determine if the input string has valid matching brackets.
Problem Understanding
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.
Example:
- Input:
s = "()[]{}"-> Output:true - Input:
s = "(]"-> Output:false - Input:
s = "([)]"-> Output:false
Algorithm Strategy
We use a Stack data structure.
- Iterate through the string char by char.
- If we see an open bracket (
(,{,[), push it onto the stack. - If we see a close bracket (
),},]), check the top of the stack:- If stack is empty, it's invalid (no matching open).
- If stack top is the matching open bracket, pop the stack.
- Otherwise, it's a mismatch -> invalid.
- At the end, stack must be empty (all opened brackets were closed).
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
Watch how the stack grows with open brackets and shrinks with matching closed ones.
Dry Run
Input: ({[]})
| Step | Char | Action | Stack |
|---|---|---|---|
| 1 | ( |
Push | ( |
| 2 | { |
Push | ( { |
| 3 | [ |
Push | ( { [ |
| 4 | ] |
Match [? Yes. Pop. |
( { |
| 5 | } |
Match {? Yes. Pop. |
( |
| 6 | ) |
Match (? Yes. Pop. |
Empty |
| End | - | Stack Empty? Yes. | Valid |
Edge Cases & Common Mistakes
- Empty String: Usually valid (unless constraints say otherwise).
- Odd Length: Automatically invalid.
- Start with Close:
]...invalid immediately. - Leftovers:
(()stack not empty at end.
Solution
Stack implementation.
1class Solution:2 def isValid(self, s: str) -> bool:3 stack = []4 mapping = {")": "(", "}": "{", "]": "["}56 for char in s:7 if char in mapping:8 # Closing bracket9 top_element = stack.pop() if stack else '#'10 if mapping[char] != top_element:11 return False12 else:13 # Opening bracket14 stack.append(char)1516 return not stack
ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
