Lesson 2 of 2
Pruning and constraints
Most choice trees are full of branches that are broken from their first wrong step. Test every choice before you make it, and the search never builds what cannot become an answer.
Say what pruning is and why a prune test must never cut a path that can still be finished
Generate balanced brackets with two counts that allow only safe choices
Use a start index and sorted choices to build each combination once, and stop a loop early with break
Search a grid by marking each cell on the path and putting its letter back afterwards
Check a queen's column and both diagonals in O(1) with three sets
Write down every balanced string of two ( and two ). Balanced means that, read left to right, each ) closes an earlier ( that is still open, and nothing is left open at the end. You would not write ))(( in full and then check it. You would stop at the first character, because a ) with nothing open can never be fixed by what comes after it.
Recall the choice tree from the last lesson. Each node (a box in that lesson's figures) is one call holding the path, the choices made so far. Each level down adds one choice, and a leaf at the bottom holds a finished path. There, every leaf was an answer: every subset, every ordering. Most backtracking problems want only the leaves that obey a rule, and most leaves break the rule long before they are finished.
This lesson teaches the search to stop early, under four rules: brackets that balance, numbers that add up to a target, a word along a path on a grid, and queens that do not attack each other. Each one adds a single test to the same template: choose, explore, unchoose (add a choice to the path, call the function again to extend it, then remove the choice so the next one starts clean).
Cut a branch the moment it breaks
How do we stop building a string that is already broken? First, the slow way. Each of the 4 positions holds ( or ), so the choice tree for 2 pairs has 2 × 2 × 2 × 2 = 16 leaves. Generate and filter builds all 16 and checks each at the end; only (()) and ()() pass. With every partial string counted, from the empty one down, the tree has 1 + 2 + 4 + 8 + 16 = 31 nodes.
Pruning, named after cutting branches off a tree, means skipping a branch the moment its path cannot lead to a valid answer. The test runs before the choice is made, so nothing below a failed choice is ever built. For brackets, two counts are enough. Let opened be the number of ( in the path and closed the number of ), with n pairs in all.
- A
(is safe whileopened < n: the string has only n of them. - A
)is safe whileclosed < opened: some(is still waiting for it.
Here is the template with those two tests. path is the list of brackets chosen so far, and each call of build is one node of the tree. The search goes depth first: it follows one branch all the way down before it backs up to try the next. Before you step through, guess how many times build is called for n = 2.
def generate_parentheses(n):out = []path = []def build(opened, closed):if len(path) == 2 * n:out.append("".join(path))returnif opened < n:path.append("(")build(opened + 1, closed)path.pop()if closed < opened:path.append(")")build(opened, closed + 1)path.pop()build(0, 0)return out
(nothing printed yet)Every branch the search entered ended in an answer. The tests are exact: they reject a bracket only when no balanced string can start that way, and they allow it whenever one can. Exact tests are rare, but every prune test has the same two jobs. It must be safe: it never cuts a path that can still be finished. And it should cut as early as it can.
Now read a pruned search with a new rule: strings of a and b with no b right after another b.
This search builds strings of a and b of length 3, but it never puts a b right after another b. Type exactly what it prints, one string per line.
def no_bb(n):
out = []
path = []
def build():
if len(path) == n:
out.append("".join(path))
return
path.append("a")
build()
path.pop()
if not path or path[-1] != "b": # prune test for "b"
path.append("b")
build()
path.pop()
build()
return out
for s in no_bb(3):
print(s)
The saving grows fast with n. Count it once by hand.
On paper, draw the tree that the bracket search builds for n = 3, one level per bracket, the way the trace built it for n = 2. Every node is one call of build, the empty root included. How many calls are there? Then compare with the full tree of every string of 0 to 6 brackets.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The solution is the trace you stepped through. For n = 12 the pruned search makes 1,033,411 calls, while the full tree has 33,554,431 nodes, about 32 times as many. Each of the 208,012 answers must still be written down, so no search can beat O(n) per answer.
Recap. A prune test runs before a choice and skips everything below a choice that cannot work. For brackets, two counts make the test exact, so no branch dies and every call is on the way to an answer.
Sorted choices: one test cuts many branches
Now the rule is a sum. Combination sum gives a list of different positive numbers, candidates, and a target. List every combination that adds up to target, where a number may be used any number of times, and each combination appears once: [2, 2, 3] and [3, 2, 2] are the same one.
The plain template, which tries every candidate at every step, has two problems here, and each has a small fix.
- The same combination in many orders. Picking freely at every step builds
[2, 2, 3],[2, 3, 2]and[3, 2, 2]as three branches. Fix: build each combination in one order only, the order of the list. A callexplore(start, remaining)triescandidates[i]only forifromstarton, and passesito the next call, so the same number may come again but an earlier one may not. - Overshooting the target. The notebook keeps
remaining, how much oftargetis still missing. If a candidate is bigger thanremaining, adding it overshoots. Fix: sort the candidates first. Then every later candidate overshoots too, so the loop canbreak(end the whole loop) instead ofcontinue(skip only this candidate). One test cuts this branch and all the branches to its right.
The trace runs on [3, 2] with target 7. Guess first: how many combinations are there, and how many times does the loop break?
def combination_sum(candidates, target):candidates = sorted(candidates)result = []path = []def explore(start, remaining):if remaining == 0:result.append(path[:])returnfor i in range(start, len(candidates)):c = candidates[i]if c > remaining:breakpath.append(c)explore(i, remaining - c)path.pop()explore(0, target)return result
(nothing printed yet)The break leans on the sort. See what happens without it.
This is the trace's code with one line taken out: it never sorts candidates. The answer should be the two combinations [2, 2, 2] and [2, 4]. Type exactly what this version prints.
def combination_sum_unsorted(candidates, target):
result = []
path = []
def explore(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break
path.append(c)
explore(i, remaining - c)
path.pop()
explore(0, target)
return result
print(combination_sum_unsorted([4, 2], 6))
The start index and the break do all the work. For candidates [2, 3, 5, 7] and target 44, the search makes 1,541 calls to find 114 combinations, each built once. The brute force, which tries every candidate at every step and stops a branch only once its sum goes over, makes about 56 million.
Change two rules and the same search fits a new problem: each number at most once, and exactly k of them.
Write pick_digits(k, n), which returns every way to choose k different digits from 1 to 9 that add up to n. Each way is a list of digits, and each way appears once: [1, 2, 4] and [4, 2, 1] are the same way. Return the ways in any order, or an empty list if there are none. (This is LeetCode 216, Combination Sum III.)
Use the combination-sum search with two changes: a digit may not be used twice, and a path stops at k digits.
raise NotImplementedError, then press Run tests. Each check says what it expects.Mark the cell, give it back
On a grid, the rule involves the path itself. Word search asks whether a word can be spelled along a path of cells on a letter grid. The path moves one cell at a time up, down, left or right, and no cell may appear twice.
The prune test is the letter. Compare one letter at a time as the path grows, and back up the moment a cell holds the wrong one. A helper match(r, c, i) answers one question: can word[i:] (the word from index i on) be spelled starting at the cell in row r, column c?
The path also has to remember its cells, so that it never steps on one twice. Keep that notebook on the board itself. When the path enters a cell, overwrite its letter with "#" (choose). When the path leaves, put the letter back (unchoose). "#" matches no letter, so the test that rejects wrong letters also rejects cells already on the path.
Module 10's depth-first search marked grid cells too, but its marks stayed: a cell reached once was done for good. Here the mark comes off when the path backs up, because a different path may need that cell.
The trace searches for "CAR" on a board of 2 rows and 3 columns. The C has an A below it and an A to its right, and only one of them leads to the R. Before you step through, guess which A the search tries first. Watch the board: marks appear as the path grows and disappear as it backs up.
def word_exists(board, word):rows, cols = len(board), len(board[0])def match(r, c, i):if r < 0 or r >= rows or c < 0 or c >= cols:return Falseif board[r][c] != word[i]:return Falseif i == len(word) - 1:return Trueletter = board[r][c]board[r][c] = "#"found = (match(r + 1, c, i + 1)or match(r - 1, c, i + 1)or match(r, c + 1, i + 1)or match(r, c - 1, i + 1))board[r][c] = letterreturn foundfor r in range(rows):for c in range(cols):if match(r, c, 0):return Truereturn False
(nothing printed yet)Putting the letter back is the line people forget. See what it protects.
This version marks each cell with "#" but never puts the letter back:
def word_exists(board, word):
rows, cols = len(board), len(board[0])
def match(r, c, i):
if r < 0 or r >= rows or c < 0 or c >= cols:
return False
if board[r][c] != word[i]:
return False
if i == len(word) - 1:
return True
board[r][c] = "#"
return (match(r + 1, c, i + 1) or match(r - 1, c, i + 1)
or match(r, c + 1, i + 1) or match(r, c - 1, i + 1))
for r in range(rows):
for c in range(cols):
if match(r, c, 0):
return True
return False
The board is one row, [["S", "A", "L", "A"]], and "ALAS" is on it, read right to left from the last cell. What does word_exists([["S", "A", "L", "A"]], "ALAS") return?
Choose one answer, then check.
Now build match from its lines. Every line has exactly one place where it works.
Put the lines of match(r, c, i) in order. As inside word_exists, it reads board, word, rows and cols from outside, and it answers: can word[i:] be spelled starting at the cell in row r, column c? Indentation is part of each line. Three lines do not belong.
One change from the trace: there is no letter name. The cell passed the check board[r][c] == word[i], so the letter to put back is word[i].
Add lines from the list below, in order.
board[r][c] = word[i]return foundreturn Truedef match(r, c, i):board[r][c] = "#"if r >= rows or c >= cols:return False # off the boardreturn False # wrong letter, or a cell already on the pathboard[r][c] = letterreturn match(r + 1, c, i + 1) or match(r - 1, c, i + 1) or match(r, c + 1, i + 1) or match(r, c - 1, i + 1)found = match(r + 1, c, i + 1) or match(r - 1, c, i + 1) or match(r, c + 1, i + 1) or match(r, c - 1, i + 1)if i == len(word) - 1:if r < 0 or r >= rows or c < 0 or c >= cols:if board[r][c] != word[i]:
The solution is the trace's code. Read its edge cases too: one shows the missing unmark from the choice above failing on another board, and one shows why the bounds check needs r < 0 as well as r >= rows.
Constraints as sets: n queens
What if the rule involves every earlier choice? A queen on a chessboard attacks every square in its row, its column and both of its diagonals, however far away. N-Queens asks for every way to place n queens on an n by n board with no two attacking.
Two queens in one row attack each other, and there are n queens for n rows, so each row holds exactly one queen, and the choice per row is its column. The brute force tries every column in every row and checks the board only when it is full: nn boards, 88 = 16,777,216 for n = 8. The search instead fills the rows top to bottom and tests each square before a queen goes there: does a queen above share its column or one of its diagonals?
Number the rows from 0 at the top and the columns from 0 at the left, so (row, col) names one square. Comparing a square with every queen above costs O(n). Three sets make it O(1), because a diagonal can be named by one number:
- Columns: the set
colsholds the column of every queen. - Down-right diagonals: a step down and to the right adds 1 to both the row and the column, so
row - colstays the same. The setdownsholdsrow - colfor every queen. - Up-right diagonals: a step up and to the right subtracts 1 from the row and adds 1 to the column, so
row + colstays the same. The setupsholdsrow + colfor every queen.
Check both: squares (0, 1), (1, 2) and (2, 3) lie on one down-right diagonal, and row - col is −1 for all three. Squares (2, 1), (1, 2) and (0, 3) lie on one up-right diagonal, and row + col is 3 for all three. Rows need no set, because each row gets one queen.
The trace sets up a 4 by 4 board with queens at row 0, column 1 and row 1, column 3, then tests every square of row 2. Here is that board, with Q for a queen and ? for the squares the trace tests:
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | . | Q | . | . |
| row 1 | . | . | . | Q |
| row 2 | ? | ? | ? | ? |
| row 3 | . | . | . | . |
Before you step through, guess which columns of row 2 are safe.
queens = [(0, 1), (1, 3)]cols, downs, ups = set(), set(), set()for row, col in queens:cols.add(col)downs.add(row - col)ups.add(row + col)row = 2for col in range(4):if col in cols or row - col in downs or row + col in ups:print(col, "attacked")else:print(col, "safe")
(nothing printed yet)Try one on a bigger board.
On a 5 by 5 board, queens stand at row 0, column 0 and at row 1, column 2. Exactly one square in row 2 is safe. Which column is it? Use the three sets: columns, row - col and row + col.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The search is a function place(row) that fills one row, started with place(0). A list queen_cols keeps the column chosen in each row so far.
- If
rowequals n, every row holds a queen. Build the answer's strings fromqueen_colsand save them. - Otherwise try each
colfrom 0 to n - 1, and skip the square if any of the three lookups hits. - For a free square: choose (append
coltoqueen_colsand addcol,row - colandrow + colto the three sets), explore (place(row + 1)), then unchoose (popqueen_colsand remove all three numbers).
Choose and unchoose change all four notebooks together, so the sets always describe exactly the queens on the board.
The solution adds one queen per call with the three sets. On a 4 by 4 board it makes 17 calls of place and finds the two placements, where the brute force builds all 44 = 256 boards.
What makes a prune test right
Four problems, one template, four tests. What changed each time was the test, and the notebook that makes it cheap:
| Problem | Prune test before a choice | Notebook that makes it O(1) |
|---|---|---|
| Balanced brackets | opened < n for (, closed < opened for ) | two counts |
| Combination sum | c > remaining, then break | remaining and a sorted list |
| Word search | the cell is on the board and holds word[i] | "#" marks on the board |
| N-Queens | the column and both diagonals are free | three sets |
Safe does not mean exact. Only the bracket tests were exact: every branch they let in ended in an answer. In the combination sum trace, [2, 2, 2] passed every test and still died with 1 missing. On a 4 by 4 board, a queen in column 0 of the top row passes every test and leads to no placement. A safe test may let a dead branch in. It must never shut a live one out.
Safe comes first. A test that is a little too strict cuts more, so the search runs faster, but it loses answers, and with no error. Here is one character changed.
This combination sum uses >= where the trace used >:
def combination_sum(candidates, target):
candidates = sorted(candidates)
result = []
path = []
def explore(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c >= remaining:
break
path.append(c)
explore(i, remaining - c)
path.pop()
explore(0, target)
return result
What does combination_sum([2, 3], 6) return?
Choose one answer, then check.
The module's practice bank has one more in this family: Cut a string into palindromes (LeetCode 131), where the test before each cut is "is this piece a palindrome?".
Last, say it the way you would in the room.
You are about to write N-Queens. Before typing, tell the interviewer your plan: the brute force and its cost, the prune test and why it is safe, the notebook that makes the test O(1), and what the search costs.
Saved in this browser as you type.