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 <= 104s 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:
Imagine you have a mixed-up string of opening and closing brackets and you need to figure out if every opening bracket is properly closed and matched in the right order. The brute force approach involves trying every possible way to pair up and cancel out matching brackets until nothing is left or you run out of options.
Here's how the algorithm would work step-by-step:
def is_valid(bracket_string):
# We repeatedly mutate the string because valid pairs must be adjacent to collapse first
current_sequence = bracket_string
while True:
previous_length = len(current_sequence)
current_sequence = current_sequence.replace("()", "")
current_sequence = current_sequence.replace("[]", "")
current_sequence = current_sequence.replace("{}", "")
# Stopping early prevents infinite loops when no more adjacent pairs can be erased
if len(current_sequence) == previous_length:
break
# Only a completely empty string proves every opening bracket found its correct match
return len(current_sequence) == 0The optimal strategy for checking valid parentheses mimics how a human would check a nested structure by keeping track of opening symbols as they appear. As closing symbols show up, they must match the most recently seen opening symbol, ensuring everything is properly nested and closed in the correct order.
Here's how the algorithm would work step-by-step:
def is_valid_parentheses(input_string):
opening_to_closing_map = {')': '(', '}': '{', ']': '['}
opening_symbol_stack = []
# We record opening symbols so we can match them against future closing symbols.
for current_character in input_string:
if current_character in opening_to_closing_map.values():
opening_symbol_stack.append(current_character)
elif current_character in opening_to_closing_map.keys():
# A closing symbol requires an immediate matching opening symbol to be valid.
if not opening_symbol_stack or opening_symbol_stack[-1] != opening_to_closing_map[current_character]:
return False
opening_symbol_stack.pop()
# Unmatched opening symbols mean the structure was never properly closed.
return len(opening_symbol_stack) == 0| Case | How to Handle |
|---|---|
| Empty string input | Return true immediately since an empty string has no unmatched brackets. |
| String with a single character | Return false because a single bracket can never be closed. |
| String starting with a closing bracket | The stack will be empty when attempting to pop, signaling an immediate invalid state and returning false. |
| String with only opening brackets | The loop finishes with elements remaining in the stack, which is caught at the end by checking if the stack is empty. |
| Mismatched closing and opening bracket types | The popped element from the stack will not match the current closing bracket, resulting in an immediate false return. |
| Maximum-sized inputs with deep nesting | The stack grows proportionally to the input size, operating in O(N) time and space complexity without stack overflow risks. |
| Interleaved or overlapping bracket types | The LIFO nature of the stack naturally enforces correct nesting order by ensuring the most recent open bracket is closed first. |
| Strings with odd lengths | An odd-length string can never have all brackets properly closed, so returning false early or relying on the final stack check handles this efficiently. |