Kodewick
Start learning →
Matching brackets14 / 52

Matching brackets

Lesson 14 of 52 · Part 3 · Stacks and queues · about 12 minutes

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:

  1. An opening bracket: push it.
  2. 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.
  3. 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.

Checking {[()]}: each opener goes on the stack; each closer is checked against the top and pops it when they pair
Choose one

While checking {[()]}, what is the largest number of brackets on the stack at once?

Choose one

You read a closing bracket and the stack is empty. What does that mean?

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.

main.py
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))
Output
'{[()]}' 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, so stack[-1] never raises IndexError on an empty list.
  • The end is return not stack, not return True: forget it and something like ((), with an opener never closed, passes as valid.
Fill inTap one to fill a blank; tap a blank to take it back

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("(()"))
Exercise 1

Write is_valid

Fill in is_valid: True when balanced, False otherwise. All three failures must be caught.

It should print
True False False False
exercise1.py
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("(()"))
Output
Press Run or Ctrl+Enter

Every way it fails

There are only three ways to fail, each found at a different moment:

ExampleWhat is wrongWhen it is found
([)]the wrong kind: the closer does not pair with the topat ), when the top is [
())a closer too many: nothing before it to pair withat the second ), when the stack is already empty
(()an opener too many: one never closedafter the end, when one ( is still on the stack

Checking ([)]: at ), the top is [. The [ opened last is still open when ) arrives: the wrong kind, so there is no need to read on

The third is the one people miss. Check only inside the loop and finish with return True, and (() passes as balanced:

main.py
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("((("))
Output
True True

Counting alone does not work either: the counts can match while the order is wrong.

main.py
1def count_only(s):2    return s.count('(') == s.count(')')3 4for s in ["(())", ")(", "())("]:5    print(s, count_only(s))
Output
(()) 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:

main.py
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))
Output
([)] 2
()) 2
(() 0
{[]} -1
Guess the outputA wrong guess is fine

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("[(]{})"))
Choose one

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?

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).

Exercise 2

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 ).

It should print
1 3 0 4
exercise2.py
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("))(("))
Output
Press Run or Ctrl+Enter

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 against pairs.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.
main.py
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("<(>)"))
Output
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.

Guess the outputA wrong guess is fine

<> 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(">"))

Summary

Take-away

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