Stack of open brackets
Push openers; on a closer, the top of the stack must be its matching opener.
Keep a stack of the brackets that are currently open. A closing bracket is only legal if the stack's top is its partner — pop it. Anything else is an immediate false. At the end, the stack must be empty.
A small pairs map (close → open) keeps the code free of a six-way if/elif chain and doubles as the “is this a closing bracket?” test.
Algorithm
- Build
pairs = { ')': '(', ']': '[', '}': '{' }and an empty stack. - For each character: if it's a closer, the stack must be non-empty and its top must equal
pairs[ch]— otherwise returnfalse. Pop. - If it's an opener, push it.
- Return
trueiff the stack is empty at the end.
- Time
- O(n)
- Space
- O(n)
Worst case (all openers) the stack holds every character.
class Solution: def isValid(self, s: str) -> bool: pairs = {")": "(", "]": "[", "}": "{"} stack: list[str] = [] for ch in s: if ch in pairs: # closing bracket if not stack or stack[-1] != pairs[ch]: return False stack.pop() else: # opening bracket stack.append(ch) return not stack