Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Examples
s = '()'
true
Single pair of parentheses.
s = '()[]{}'true
All brackets are matched correctly.
s = '(]'
false
'(' is matched with ']' which is invalid.
Constraints
- •
1 <= s.length <= 10^4 - •
s consists of parentheses only '()'[]{}'.
Approaches
Repeatedly replace matching pairs until no more can be found.
def is_valid(s):
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('()', '').replace('[]', '').replace('{}', '')
return len(s) == 0Use a stack to push opening brackets and pop when a matching closing bracket is found.
def is_valid(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
return len(stack) == 0Same stack approach with early termination on odd length.
Diagram
def is_valid(s):
if len(s) % 2 != 0:
return False
stack = []
pairs = {'(': ')', '[': ']', '{': '}'}
for char in s:
if char in pairs:
stack.append(char)
elif not stack or pairs[stack.pop()] != char:
return False
return not stackComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Iterative Replacement | O(n^2) | O(n) | Repeatedly replace matching pairs until no more can be found. |
| Stack | O(n) | O(n) | Use a stack to push opening brackets and pop when a matching closing bracket is found. |
| Stack with Early Termination | O(n) | O(n) | Same stack approach with early termination on odd length. |
Repeatedly replace matching pairs until no more can be found.
Use a stack to push opening brackets and pop when a matching closing bracket is found.
Same stack approach with early termination on odd length.
Common Mistakes
Forgetting to check if the stack is empty before popping
Not handling the case where the stack is non-empty at the end
Using the wrong mapping direction (should map closing to opening)