py_bracket_validator — Balanced Bracket Checker
Difficulty: medium
Write a function that checks if brackets [], parentheses (), and braces {} are properly balanced and correctly nested in a string. All other characters are ignored. Return True if balanced, False otherwise.
def bracket_validator(s: str) -> bool:
Examples
>>> bracket_validator("()")
True
>>> bracket_validator("()[]{}")
True
>>> bracket_validator("(]")
False
>>> bracket_validator("([)]")
False
>>> bracket_validator("{[]}")
True
>>> bracket_validator("hello(world)[test]{code}")
True
>>> bracket_validator("((()))")
True
>>> bracket_validator("((())")
False
>>> bracket_validator("")
True
Solution
Download py_bracket_validator.pydef bracket_validator(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
openers = set("([{")
stack = []
for ch in s:
if ch in openers:
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return not stack
How It Works
Goal: Verify every opening bracket has a matching closer in the correct order.
Approach: Use a stack — push openers, and on a closer pop and check it matches the most recent opener.
Step by step:
- For each character, ignore anything that is not a bracket character.
- On an opener (
(,[,{), push it onto the stack. - On a closer (
),],}), check that the top of the stack is the matching opener. If not (or the stack is empty), returnFalse. - After scanning, the stack must be empty — otherwise an opener was never closed.
Key concept: Stacks are the natural data structure for matching nested pairs because the most recently opened context is always the first that must be closed (LIFO).