Full answer
Problem
Given a string containing ()[]{} and possibly other characters, return True if brackets are balanced and properly nested.
Example: "{[]}" is valid, "([)]" is not, "f(a[i]) + {x}" is valid (other characters are ignored).
Constraints: 0 <= len(s) <= 10^4.
Brute force
Repeatedly delete adjacent pairs "()", "[]", "{}" until nothing changes; valid if the string ends empty. O(n^2) in the worst case.
Optimal approach
- Map each closer to its opener:
{")": "(", "]": "[", "}": "{"}. - For each character: push openers; for a closer, return
Falseif the stack is empty or the popped opener does not match. - Return
Trueonly if the stack is empty at the end.
Why it works
Proper nesting means the most recently opened bracket must close first, which is exactly last in, first out. The stack holds unmatched openers in order; each closer must match the latest one. Leftover openers at the end were never closed.
A single counter works only for one type: it accepts "([)]" because the counts balance, even though the order is wrong.
Complexity
O(n) time, O(n) space in the worst case (all openers).
Code
def is_valid(s):
"""True if every bracket is closed by the same type in the right order. O(n)."""
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
# other characters are ignored
return not stack
if __name__ == "__main__":
assert is_valid("()") is True
assert is_valid("()[]{}") is True
assert is_valid("(]") is False
assert is_valid("([)]") is False
assert is_valid("{[]}") is True
assert is_valid("") is True
assert is_valid("(") is False
assert is_valid(")") is False
assert is_valid("f(a[i]) + {x}") is True
print("all tests passed")Save as a36_valid_parentheses.py and run python3 a36_valid_parentheses.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string is valid. A lone closer (")") is invalid because the stack is empty. A lone opener is invalid because the stack is not empty at the end. Non-bracket characters are skipped. Odd length containing only brackets can be rejected early as an optimisation.
Pattern
Stack for matching nested structure. Related: minimum additions to make brackets valid, longest valid parentheses, evaluating expressions, HTML or XML tag matching, and checking balanced code blocks in editors.
def is_valid(s):
"""True if every bracket is closed by the same type in the right order. O(n)."""
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
# other characters are ignored
return not stack
if __name__ == "__main__":
assert is_valid("()") is True
assert is_valid("()[]{}") is True
assert is_valid("(]") is False
assert is_valid("([)]") is False
assert is_valid("{[]}") is True
assert is_valid("") is True
assert is_valid("(") is False
assert is_valid(")") is False
assert is_valid("f(a[i]) + {x}") is True
print("all tests passed")Stack with a closer-to-opener map; ignores non-bracket characters.
Complexity
Time: O(n). Space: O(n). The repeated-deletion brute force is O(n^2).
By level
Fresher: Explains last in, first out matching, writes the stack solution and tests the main invalid cases. Should test a lone opener and a lone closer.
Mid: Explains why counters fail for mixed types and extends to reporting error positions. Reports the index of the first error.
Senior: Connects to parsing and grammars, handles very long inputs or streaming, and solves the longest valid parentheses variant. Can explain how the same method checks nested tags in markup.
Key points
- Push openers, match closers against the top
- Empty stack on a closer means invalid
- Leftover openers mean invalid
- A counter fails for mixed bracket types
- O(n) time
Common mistakes
- Using one counter for all bracket types
- Popping without checking for an empty stack
- Forgetting to check the stack is empty at the end
- Treating other characters as errors without stating the rule
Follow-ups
- What is the minimum number of insertions to make a string valid?
- How would you find the longest valid parentheses substring?
- How would you report the position of the first error?
Tips
- Give the "([)]" counterexample for a counter
- State the map from closers to openers
- Test a lone closer and a lone opener
Evaluation rubric
- Correct stack logic
- Handles empty and unbalanced cases
- Correct complexity
- Explains why a stack is needed