NeetCode 150, stage 10: Backtracking

← Heap and Priority Queue Ā· All 150 problems Ā· Graphs →

Backtracking builds each answer one choice at a time, and it goes back when a choice cannot lead to an answer. This stage trains the problems that say ā€œall subsetsā€, ā€œall combinationsā€ or ā€œall permutationsā€. Each solution has the same three moves: choose, explore, undo. In Go, this stage also teaches when a saved slice needs a copy.

Garden notes: the Go syntax for this stage.

Problems on this page

Templates to memorize

Template A: Choose, explore, undo with a start index

Signal

The problem asks for all subsets or all combinations. The order of the items in one answer does not matter, so [1, 2] and [2, 1] are the same answer.

// TEMPLATE A: choose, explore, undo with a start index.
// This example builds each group of k items. The order in a group does not
// matter.
func groupsOfK(items []int, k int) [][]int {
    res := [][]int{}
    path := []int{} // the choices so far
    var dfs func(start int)
    dfs = func(start int) {
        if len(path) == k { // GOAL
            // SAVE a copy, never the path itself
            res = append(res, slices.Clone(path))
            return
        }
        for i := start; i < len(items); i++ {
            path = append(path, items[i]) // 1. CHOOSE
            // 2. EXPLORE. i+1: no reuse. i: reuse is allowed
            dfs(i + 1)
            path = path[:len(path)-1] // 3. UNDO
        }
    }
    dfs(0)
    return res
}

The moves are CHOOSE, EXPLORE, then UNDO. The start index gives each answer one fixed order, so no answer appears two times. Pass i + 1 when each item can be used one time, and pass i when an item can repeat. Save slices.Clone(path), not path. All the saved slices would share one backing array, and the later appends would write over them.

Say it

ā€œI build the answer one item at a time: choose, recurse, undo. A start index stops duplicates, and I copy the path before I save it.ā€

Template B: Skip duplicates after a sort

Signal

The input can contain equal values, and the answer must not contain the same subset or combination two times.

// TEMPLATE B: the input has equal values. Sort, then skip an equal value in
// the same loop.
func uniqueGroupsOfK(items []int, k int) [][]int {
    sort.Ints(items) // 1. SORT: equal values become neighbors
    res := [][]int{}
    path := []int{}
    var dfs func(start int)
    dfs = func(start int) {
        if len(path) == k {
            res = append(res, slices.Clone(path))
            return
        }
        for i := start; i < len(items); i++ {
            if i > start && items[i] == items[i-1] {
                // 2. SKIP: this value already opened a branch in this loop
                continue
            }
            path = append(path, items[i])
            dfs(i + 1)
            path = path[:len(path)-1]
        }
    }
    dfs(0)
    return res
}

The moves are SORT, then SKIP. The rest is Template A. The test is i > start, not i > 0. It stops a second equal value in the same loop, at the same depth. A deeper call can still choose the next equal value, so [2, 2] stays possible.

Say it

ā€œI sort first, so equal values are neighbors. At each depth I use a value only one time, and that removes the duplicate answers without a set.ā€

Template C: Permutations with a used slice

Signal

The problem asks for all orders or all arrangements. The order matters, so [1, 2] and [2, 1] are different answers.

// TEMPLATE C: permutations. The order matters, so each call looks at all
// the items.
func allOrders(items []int) [][]int {
    res := [][]int{}
    path := []int{}
    used := make([]bool, len(items)) // used[i]: items[i] is in the path
    var dfs func()
    dfs = func() {
        if len(path) == len(items) { // GOAL
            res = append(res, slices.Clone(path)) // SAVE a copy
            return
        }
        for i := 0; i < len(items); i++ {
            if used[i] {
                continue // 1. CHECK: each item one time
            }
            used[i] = true // 2. CHOOSE
            path = append(path, items[i])
            dfs()                     // 3. EXPLORE
            path = path[:len(path)-1] // 4. UNDO the two changes
            used[i] = false
        }
    }
    dfs()
    return res
}

The moves are CHECK, CHOOSE, EXPLORE, then UNDO. There is no start index, because a later position can take an earlier item. The used slice replaces it. The undo has two parts: remove the item from the path, and set used[i] back to false.

Say it

ā€œEach position can take each item that is not used. A boolean slice records the used items. There are n factorial permutations, so the time is O(n times n factorial).ā€

Template D: Grid path with mark and unmark

Signal

You must find a path of neighbor cells in a grid, and the path cannot use a cell two times. The path must match a word or a rule, step by step.

// TEMPLATE D: a path in a grid. The DFS marks a cell while the cell is in
// the path.
// Call it from each cell with k = 0.
func pathFrom(grid [][]byte, r, c int, word string, k int) bool {
    if k == len(word) {
        return true // GOAL: all the letters matched
    }
    if r < 0 || r >= len(grid) || c < 0 || c >= len(grid[0]) || grid[r][c] != word[k] {
        return false // 1. CHECK: in the grid, and the letter is correct
    }
    grid[r][c] = '#' // 2. MARK: this path cannot use the cell again
    found := pathFrom(grid, r+1, c, word, k+1) || pathFrom(grid, r-1, c, word, k+1) ||
        // 3. EXPLORE
        pathFrom(grid, r, c+1, word, k+1) || pathFrom(grid, r, c-1, word, k+1)
    grid[r][c] = word[k] // 4. UNMARK
    return found
}

The moves are CHECK, MARK, EXPLORE, then UNMARK. The mark is a change of the cell, so the grid is its own visited set. Always unmark before the return. If you return early when a neighbor finds the word, the grid stays damaged for the caller.

Say it

ā€œI run a DFS from each cell. I mark the cell while it is on the path and restore it when I come back, so the extra space is only the recursion.ā€

Template E: Cut a string into parts

Signal

You must split a string into parts, each part must pass a test, and the problem asks for all the ways. The test can be ā€œis a palindromeā€ or ā€œis a valid numberā€.

// TEMPLATE E: cut a string into parts. Each part must pass the valid
// function.
func cutAll(s string, valid func(part string) bool) [][]string {
    res := [][]string{}
    path := []string{}
    var dfs func(start int)
    dfs = func(start int) {
        if start == len(s) { // GOAL: the parts cover the full string
            res = append(res, slices.Clone(path)) // SAVE a copy
            return
        }
        for end := start + 1; end <= len(s); end++ {
            if !valid(s[start:end]) {
                continue // 1. CHECK the part s[start:end]
            }
            // 2. CHOOSE where this part ends
            path = append(path, s[start:end])
            dfs(end)                  // 3. EXPLORE: cut the rest
            path = path[:len(path)-1] // 4. UNDO
        }
    }
    dfs(0)
    return res
}

The moves are CHECK, CHOOSE, EXPLORE, then UNDO. The choice is the place where the next part ends. The index end is exclusive, so the loop goes up to len(s) with <=. The goal is start == len(s): the parts then cover the full string.

Say it

ā€œAt each index I try each end for the next part. If the part is valid, I recurse on the rest of the string.ā€

Template F: One choice for each position, with sets

Signal

The answer has a fixed number of positions, and each position gets one of a few options. A rule can forbid some pairs of choices, as in N-Queens.

// TEMPLATE F: one choice for each position. Here a position is a row of a
// chess board,
// and three sets tell in O(1) if a queen can go in column c.
func countQueens(n int) int {
    cols := make([]bool, n)   // cols[c]: a queen is in column c
    diag := make([]bool, 2*n) // diag[r+c]: r+c is the same on one "/" line
    // anti[r-c+n]: r-c is the same on one "\" line
    anti := make([]bool, 2*n)
    count := 0
    var dfs func(r int)
    dfs = func(r int) {
        if r == n { // GOAL: each position has its choice
            count++
            return
        }
        for c := 0; c < n; c++ {
            if cols[c] || diag[r+c] || anti[r-c+n] {
                continue // 1. CHECK the sets
            }
            // 2. PLACE
            cols[c], diag[r+c], anti[r-c+n] = true, true, true
            // 3. EXPLORE the next position
            dfs(r + 1)
            // 4. REMOVE
            cols[c], diag[r+c], anti[r-c+n] = false, false, false
        }
    }
    dfs(0)
    return count
}

The moves are CHECK, PLACE, EXPLORE, then REMOVE. The DFS index is the position, and the loop goes through the options for that position. The sets make the check O(1). On a chess board, r + c identifies one diagonal and r - c identifies the other. If no rule connects the positions, remove the sets and keep the rest.

Say it

ā€œI place one queen in each row. Three sets, for the column and the two diagonals, tell me in constant time if a cell is safe.ā€

Mistakes in this stage

  • res = append(res, path) saves a slice header that points to the memory of path. Save slices.Clone(path) or append([]int(nil), path...).
  • A recursive closure needs two lines: var dfs func(start int) first, then dfs = func(start int) {...}. With :=, the name does not exist inside its own body.
  • path[:len(path)-1] removes the last item, but it keeps the memory. The next append writes to the same place.
  • The undo must be the exact opposite of the choice. If it is not, the next branch starts from a wrong state.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

78. Subsets

LeetCode 78 Ā· Medium

39. Combination Sum

LeetCode 39 Ā· Medium

46. Permutations

LeetCode 46 Ā· Medium

90. Subsets II

LeetCode 90 Ā· Medium

40. Combination Sum II

LeetCode 40 Ā· Medium

LeetCode 79 Ā· Medium

131. Palindrome Partitioning

LeetCode 131 Ā· Medium

17. Letter Combinations of a Phone Number

LeetCode 17 Ā· Medium

51. N-Queens

LeetCode 51 Ā· Hard


← Heap and Priority Queue Ā· All 150 problems Ā· Graphs →