Matching brackets
Bracket matching uses a stack: push each opening bracket, check each closing one against the top, and require an empty stack at the end, so {[()]} is balanced and ([)] is not.
{[()]} is balanced and ([)] is not: both have the same number of brackets, but ) arrives while [ is still open. Bracket colouring in an editor, a JSON parser's "expected ] at line 2, column 17", Python's own SyntaxError: '(' was never closed: they all answer this question. The rule is: the last one opened must be the first one closed. That is exactly a stack: one pass from left to right, each character goes on and off the stack at most once, so even a 100,000-character file is O(n).
The rule: openers go on, closers check the top
Read from left to right:
- An opening bracket: push it.
- A closing bracket: if the stack is empty, there is nothing before it to pair with, so it fails; if the top is not its partner, it fails; if it is, pop.
- At the end: anything left on the stack is an opener never closed, so it fails; an empty stack means balanced.
The stack always holds the openers that are open and not yet closed, and its top is the one opened most recently.
{index 0[index 1(index 2While checking {[()]}, what is the largest number of brackets on the stack at once?
{, [ and ( are all pushed before the first closing bracket ) arrives, so at that point there are 3. After that each closing bracket pops one. The deeper the nesting, the more the stack holds at its fullest.You read a closing bracket and the stack is empty. What does that mean?
) in ()). An opening bracket that is never closed only shows up at the end, when something is left on the stack.The pairs in a dict
Which closer goes with which opener fits in a dict: the key is a closer, the value is the opener it needs. On a closer, pairs[ch] is what the top should be.
1def is_valid(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in '([{':6 stack.append(ch)7 elif ch in pairs:8 if not stack or stack[-1] != pairs[ch]:9 return False10 stack.pop()11 return not stack12 13for s in ["{[()]}", "([)]", "())", "(()", "", "print(a[0] + f(b, {1: 2}))"]:14 print(repr(s), is_valid(s))
'{[()]}' True
'([)]' False
'())' False
'(()' False
'' True
'print(a[0] + f(b, {1: 2}))' True
A few details:
- Characters that are not brackets take neither branch and are skipped, so it can check a whole line of real code (the last example).
not stack or …must come in that order: on an empty stack it returns first, sostack[-1]never raisesIndexErroron an empty list.- The end is
return not stack, notreturn True: forget it and something like((), with an opener never closed, passes as valid.
Pick what goes in the blank: what should it return after the last character?
1def is_valid(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in '([{':6 stack.append(ch)7 elif ch in pairs:8 if not stack or stack[-1] != pairs[ch]:9 return False10 stack.pop()11 return 12 13print(is_valid("{[()]}"), is_valid("([)]"), is_valid("(()"))
not stack is True when the stack is empty and False when something is left, which is exactly the answer.Write is_valid
✓Fill in is_valid: True when balanced, False otherwise. All three failures must be caught.
True False False False
1def is_valid(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 pass # opener: push; closer: empty or no pair gives False, a pair pops6 return True # at the end the stack must be empty7 8print(is_valid("{[()()]}"), is_valid("([)]"), is_valid("())"), is_valid("(()"))
Every way it fails
There are only three ways to fail, each found at a different moment:
| Example | What is wrong | When it is found |
|---|---|---|
([)] | the wrong kind: the closer does not pair with the top | at ), when the top is [ |
()) | a closer too many: nothing before it to pair with | at the second ), when the stack is already empty |
(() | an opener too many: one never closed | after the end, when one ( is still on the stack |
(index 0[index 1 · got ), no pairThe third is the one people miss. Check only inside the loop and finish with return True, and (() passes as balanced:
1def is_valid_wrong(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in '([{':6 stack.append(ch)7 elif ch in pairs:8 if not stack or stack[-1] != pairs[ch]:9 return False10 stack.pop()11 return True # forgot to look at what is left12 13print(is_valid_wrong("(()"), is_valid_wrong("((("))
True True
Counting alone does not work either: the counts can match while the order is wrong.
1def count_only(s):2 return s.count('(') == s.count(')')3 4for s in ["(())", ")(", "())("]:5 print(s, count_only(s))
(()) True )( True ())( True
)( has equal counts, but there is nothing before the first ). With only one kind of bracket you can skip the stack and keep a counter depth: add one for (, subtract one for ), fail the moment it goes negative, and require 0 at the end. With several kinds, a counter cannot remember *which kind* was opened last, so you need the stack.
To know where it fails, return an index. For a failure found only at the end (an opener never closed), return the position of the first opener left open, so the stack holds indexes:
1def first_error(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = [] # indexes of openers4 for i, ch in enumerate(s):5 if ch in '([{':6 stack.append(i)7 elif ch in pairs:8 if not stack or s[stack[-1]] != pairs[ch]:9 return i10 stack.pop()11 return stack[0] if stack else -112 13for s in ["([)]", "())", "(()", "{[]}"]:14 print(s, first_error(s))
([)] 2
()) 2
(() 0
{[]} -1
Checking [(]{}), what does it print?
1def first_error(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for i, ch in enumerate(s):5 if ch in '([{':6 stack.append(i)7 elif ch in pairs:8 if not stack or s[stack[-1]] != pairs[ch]:9 return i10 stack.pop()11 return stack[0] if stack else -112 13print(first_error("[(]{})"))
[ and (, both pushed, so the top is (. Index 2 is ], which needs [, but the top is (: the wrong kind, return 2. The {}) after it is never read; it can stop as soon as it finds an error.With only ( and ), check ())( with a counter depth: add one for (, take one away for ). At which character can you already tell it is wrong?
), there is no open ( left. Going negative along the way means wrong, so you can stop reading. depth does end at exactly 0, so looking only at the end would call it valid; that is why you check along the way too.In interviews: "Valid parentheses" is the classic first stack problem. Expect follow-ups: with one kind of bracket, can you do it without a stack (a counter that never goes negative); is the empty string valid (yes); what about brackets inside quotes (skip from a quote until it closes).
The fewest brackets to add
✓The string holds only ( and ). What is the fewest brackets you must add to balance it? Keep a counter open_count of ( not yet closed: a ) with no ( to pair with needs a ( added; each ( still open at the end needs a ).
1 3 0 4
1def min_add(s):2 open_count = 0 # ( not yet closed3 need = 0 # brackets to add4 for ch in s:5 pass6 return need7 8print(min_add("())"), min_add("((("), min_add("()()"), min_add("))(("))
How you write it at work
The standard library has no separate "match brackets" function: real parsers (json.loads, Python's own compiler) check brackets while reading the whole grammar, and report a line and column when it fails. To check a piece of text yourself, the dozen lines above are the standard way: one pairs dict and a list as the stack.
- The kinds of brackets live in the dict; adding one (say
<>) is one line,pairs['>'] = '<', with openers checked againstpairs.values(). - To report a position, push indexes (
enumerate), not characters. - Real code has brackets in strings like
")"and comments like# (, which have to be skipped first; that is why real code is checked with a parser, not this function.
1pairs = {')': '(', ']': '[', '}': '{', '>': '<'}2opens = set(pairs.values())3 4def is_valid(s):5 stack = []6 for ch in s:7 if ch in opens:8 stack.append(ch)9 elif ch in pairs:10 if not stack or stack.pop() != pairs[ch]:11 return False12 return not stack13 14print(is_valid("list<dict<str, int>>"), is_valid("<(>)"))
True False
Here "look at the top" and "pop" are one expression, stack.pop() != pairs[ch]: when they do not pair it returns False straight away, so popping does no harm.
<> has been added as another kind of bracket. What does this print?
1pairs = {')': '(', ']': '[', '}': '{', '>': '<'}2opens = set(pairs.values())3 4def is_valid(s):5 stack = []6 for ch in s:7 if ch in opens:8 stack.append(ch)9 elif ch in pairs:10 if not stack or stack.pop() != pairs[ch]:11 return False12 return not stack13 14print(is_valid("a<b>(c)"), is_valid("[<]>"), is_valid(">"))
a<b>(c): letters are skipped, <> and () each pair up, and the stack ends empty: True. [<]>: at ] the top is <, a mismatch: False. >: the stack is empty when it arrives, one closing bracket too many: False.Summary
Matching brackets: the last opened is the first closed
- An opener: push; a closer: an empty stack or no pair with the top fails, a pair pops
- At the end the stack must be empty: finish with return not stack
- The pairs as a dict: the key is a closer, the value the opener it needs
- One kind of bracket can use a counter that never goes negative; equal counts are not enough
1pairs = {')': '(', ']': '[', '}': '{'}2if ch in '([{': stack.append(ch)3elif ch in pairs:4 if not stack or stack.pop() != pairs[ch]: return False5return not stack