iq.lab
Python starts when a code cell comes near or you run one
11 Backtracking

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.

About 2 hours 15 minutes, with the 4 problems worked in it
By the end you can
  • 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 while opened < n: the string has only n of them.
  • A ) is safe while closed < 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.

Step throughOnly safe brackets, for n = 2
Step 1 of 61
Line 1 is about to run.
def generate_parentheses(n):
out = []
path = []
def build(opened, closed):
if len(path) == 2 * n:
out.append("".join(path))
return
if 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
Names
no names yet
Output
(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.

PredictNo b after a 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 paperCount the pruned tree for n = 3

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.

calls of build for n = 3

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

mediumBacktracking target 25 min

Generate balanced parentheses

You get a whole number n. Return every string made of exactly n opening brackets ( and n closing brackets ) that is balanced: read left to right, every ) closes an earlier ( that is still open, and no ( is left open at the end.

So (()) and ()() are balanced. )( is not, because its ) has nothing to close, and (() is not, because one ( is never closed.

Return a list of strings that holds each balanced string exactly once, in any order.

Example 1
Inputn = 2Output["(())", "()()"]

Two of each bracket can be arranged in 6 ways, and only these 2 are balanced. For example, ())( fails at its third character: a ) with nothing open.

Example 2
Inputn = 3Output["((()))", "(()())", "(())()", "()(())", "()()()"]

5 of the 20 arrangements of three of each bracket are balanced.

Example 3
Inputn = 1Output["()"]

)( uses the same two brackets, but its ) comes before any (.

Constraints
  • 1 ≤ n ≤ 12

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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 call explore(start, remaining) tries candidates[i] only for i from start on, and passes i to 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 of target is still missing. If a candidate is bigger than remaining, adding it overshoots. Fix: sort the candidates first. Then every later candidate overshoots too, so the loop can break (end the whole loop) instead of continue (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?

Step throughSorted candidates and an early break
Step 1 of 85
Line 1 is about to run.
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
Names
no names yet
Output
(nothing printed yet)

The break leans on the sort. See what happens without it.

PredictA break without the sort

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))
mediumBacktracking target 25 min

Combination sum

You get a list candidates of different positive integers and a positive integer target. A combination is a group of numbers taken from candidates whose total is exactly target. A group can take the same candidate as many times as you like: with candidates [4, 2, 7] and target 8, [2, 2, 2, 2] counts. Return every combination, as a list of lists.

Two combinations are the same when they use the same numbers the same number of times, in any order: [2, 2, 4] and [4, 2, 2] are one combination, so it appears once. Return the combinations in any order, and the numbers inside each in any order. If no combination works, return an empty list.

Example 1
Inputcandidates = [4, 2, 7], target = 8Output[[2, 2, 2, 2], [2, 2, 4], [4, 4]]

The 7 never fits: alone it is 1 short, and adding even a 2 goes over.

Example 2
Inputcandidates = [5, 3], target = 11Output[[3, 3, 5]]

3 + 3 + 5 = 11 is the only way. Only 3s give 9 or 12, never 11, and two 5s leave 1, which nothing fills.

Example 3
Inputcandidates = [4, 6], target = 9Output[]

Sums of 4s and 6s are always even, so 9 is out of reach.

Constraints
  • 1 ≤ len(candidates) ≤ 30

  • 2 ≤ candidates[i] ≤ 40, and all candidates are different.

  • 1 ≤ target ≤ 50

  • The answer has at most 500 combinations.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Code itk different digits that add up to n

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

Step throughMark the cell, then give it back
Step 1 of 81
Line 1 is about to run.
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
letter = 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] = letter
return found
for r in range(rows):
for c in range(cols):
if match(r, c, 0):
return True
return False
Names
no names yet
Output
(nothing printed yet)

Putting the letter back is the line people forget. See what it protects.

Quick checkThe letter that never goes back

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 in orderBuild match

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

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • board[r][c] = word[i]
    • return found
    • return True
    • def match(r, c, i):
    • board[r][c] = "#"
    • if r >= rows or c >= cols:
    • return False # off the board
    • return False # wrong letter, or a cell already on the path
    • board[r][c] = letter
    • 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)
    • 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]:
    mediumBacktrackingDepth-first search target 25 min

    You get a grid of letters board (a list of rows, each row a list of one-letter strings) and a string word. Return True if word can be spelled along a path on the board, and False otherwise.

    A path starts on any cell and moves one cell at a time up, down, left or right, never diagonally. The cells along the path, in order, must hold the letters of word, and no cell may appear twice on one path. Two cells that hold the same letter are still two different cells.

    Your function may change cells while it searches, but board must hold its original letters again when the function returns.

    Example 1
    Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "CORE"OutputTrue

    Start on the C at the top left, step down to O, right to R, and right again to E.

    Example 2
    Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "RARE"OutputFalse

    From the only R, step up to A. The only R next to that A is the one already on the path, and a cell cannot be used twice.

    Example 3
    Inputboard = [["C", "A", "T"], ["O", "R", "E"], ["D", "E", "N"]], word = "ACORN"OutputFalse

    A, C, O and R join up, but the only N touches that R at a corner. Diagonal steps are not allowed.

    Constraints
    • 1 ≤ number of rows, number of columns ≤ 6

    • 1 ≤ len(word) ≤ 15

    • board and word hold only English letters.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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 cols holds 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 - col stays the same. The set downs holds row - col for 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 + col stays the same. The set ups holds row + col for 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 0col 1col 2col 3
    row 0.Q..
    row 1...Q
    row 2????
    row 3....

    Before you step through, guess which columns of row 2 are safe.

    Step throughThree sets answer "is this square attacked?"
    Step 1 of 26
    Line 1 is about to run.
    Two queens placed: (row 0, column 1) and (row 1, column 3).
    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 = 2
    for 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")
    Names
    no names yet
    Output
    (nothing printed yet)

    Try one on a bigger board.

    Work it outThe one safe square

    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.

    column

    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.

    1. If row equals n, every row holds a queen. Build the answer's strings from queen_cols and save them.
    2. Otherwise try each col from 0 to n - 1, and skip the square if any of the three lookups hits.
    3. For a free square: choose (append col to queen_cols and add col, row - col and row + col to the three sets), explore (place(row + 1)), then unchoose (pop queen_cols and remove all three numbers).

    Choose and unchoose change all four notebooks together, so the sets always describe exactly the queens on the board.

    hardBacktracking target 40 min

    Place n queens

    A queen on a chessboard attacks every square in its row, in its column, and along both of its diagonals, however far away. You get a whole number n. Return every way to place n queens on an n by n board so that no queen attacks another.

    Write each placement as a list of n strings, one per row from top to bottom. Each string has n characters: "Q" for a square with a queen and "." for an empty square.

    Return each placement once, in any order. If there is no placement, return an empty list.

    Example 1
    Inputn = 4Output[[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]

    Counting columns from 0, the first placement has its queens in columns 1, 3, 0, 2 from the top row down. The second is its mirror image: 2, 0, 3, 1.

    Example 2
    Inputn = 1Output[["Q"]]

    One queen on one square has nothing to attack.

    Example 3
    Inputn = 3Output[]

    Wherever the top queen stands, the middle row has at most one safe square, and a queen there leaves the bottom row with none.

    Constraints
    • 1 ≤ n ≤ 9

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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:

    ProblemPrune test before a choiceNotebook that makes it O(1)
    Balanced bracketsopened < n for (, closed < opened for )two counts
    Combination sumc > remaining, then breakremaining and a sorted list
    Word searchthe cell is on the board and holds word[i]"#" marks on the board
    N-Queensthe column and both diagonals are freethree 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.

    Quick checkOne character too strict

    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.

    Say itPlan N-Queens out loud

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint