Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to checking if parentheses are valid means we're going to try to remove matching pairs one by one until we either have no parentheses left (valid) or can't remove any more (invalid). It's like peeling layers of an onion until you get to the core.
Here's how the algorithm would work step-by-step:
def is_valid_parentheses_brute_force(input_string):
mutable_string = list(input_string)
while True:
found_match = False
index = 0
while index < len(mutable_string) - 1:
# Check for matching parentheses pairs
if (mutable_string[index] == '(' and mutable_string[index + 1] == ')') or \
(mutable_string[index] == '[' and mutable_string[index + 1] == ']') or \
(mutable_string[index] == '{' and mutable_string[index + 1] == '}'):
# Remove the matching pairs
mutable_string.pop(index + 1)
mutable_string.pop(index)
found_match = True
# Reset the index to the beginning
index = 0
continue
index += 1
# If no matching pairs were found, break the loop
if not found_match:
break
# Check if the string is empty after removing matching pairs
if not mutable_string:
return True
else:
return False
The best way to check if parentheses are valid is to use a stack-like structure to keep track of opening parentheses. We'll go through the input step by step, making sure each closing parenthesis has a matching opening parenthesis.
Here's how the algorithm would work step-by-step:
def isValid(input_string): parenthesis_stack = []
parenthesis_map = {
')': '(',
']': '[',
'}': '{'
}
for char in input_string:
if char in parenthesis_map:
# Closing parenthesis found, check for match
if not parenthesis_stack or parenthesis_stack[-1] != parenthesis_map[char]:
return False
parenthesis_stack.pop()
else:
# Opening parenthesis found, add to stack
parenthesis_stack.append(char)
# Stack must be empty for valid parentheses
return not parenthesis_stack
Case | How to Handle |
---|---|
Empty string input | Return true since an empty string is considered valid. |
Null string input | Return true if a null string is considered valid; otherwise, throw an IllegalArgumentException or return false. |
String with a single opening bracket | Return false, as there's no corresponding closing bracket. |
String with a single closing bracket | Return false, as there's no corresponding opening bracket. |
String with mismatched brackets, e.g., '(]' | Return false, as the closing bracket doesn't match the last opened bracket. |
String with correctly nested brackets but incorrect order, e.g., '(){}' | The stack should not be empty at the end if order is incorrect, resulting in returning false. |
String with only opening brackets, e.g., '((({' | The stack will not be empty if only opening brackets exist, leading to returning false. |
Very long string (potential stack overflow) | Ensure the stack implementation used (explicit or implicit) is memory efficient, especially for deep nesting, and avoid unbounded recursion. |