Pattern #21

Backtracking

Important interview questions, thinking patterns, choice trees, pruning, slice mutation traps in Go, and rules for solving backtracking problems.

Must Solve

16 core questions — solve these first.

  1. 1.Subsets
    medium
  2. 2.Subsets II
    medium
  3. 3.Permutations
    medium
  4. 4.Permutations II
    medium
  5. 5.Combination Sum
    medium
  6. 6.Combination Sum II
    medium
  7. 7.Generate Parentheses
    medium
  8. 8.Letter Combinations of a Phone Number
    medium
  9. 9.Word Search
    medium
  10. 10.Palindrome Partitioning
    medium
  11. 11.N-Queens
    hard
  12. 12.N-Queens II
    hard
  13. 13.Sudoku Solver
    hard
  14. 14.Restore IP Addresses
    medium
  15. 15.Combination Sum III
    medium
  16. 16.Word Search II
    hard

Also Important

9 more questions worth practicing.

  1. 17.Combinations
    medium
  2. 18.Beautiful Arrangement
    medium
  3. 19.Matchsticks to Square
    medium
  4. 20.Partition to K Equal Sum Subsets
    medium
  5. 21.Letter Tile Possibilities
    medium
  6. 22.Split a String Into the Max Number of Unique Substrings
    medium
  7. 23.Maximum Length of a Concatenated String with Unique Characters
    medium
  8. 24.Rat in a Maze
    medium
  9. 25.Graph Coloring Problem
    medium

How to Think

  1. Need all possible answers?Backtracking
  2. Need try different choices?Choose, Explore, Undo
  3. Need permutations / subsets / combinations?Backtracking
  4. Need place things with rules (N-Queens, Sudoku)?Backtracking
  5. Need search a path in grid?DFS + Backtracking
  6. Need stop bad paths early?Pruning

Go Backtracking Template (with Slice Copy Protection)

Universal Backtracking Template in Go

func backtrack(path []int, choices []int) {
    if isComplete(path) {
        // IMPORTANT: Make an explicit slice copy in Go!
        copyPath := append([]int(nil), path...)
        results = append(results, copyPath)
        return
    }

    for _, choice := range choices {
        if isValid(choice) {
            // 1. Choose
            path = append(path, choice)

            // 2. Explore
            backtrack(path, choices)

            // 3. Undo
            path = path[:len(path)-1]
        }
    }
}

👉 Always copy slices before appending to results to avoid mutation bugs!

Core Backtracking Pattern & Pruning

1. Choose

Make decision: Add item/digit/board position to current path state.

2. Explore

Recurse to next step or next index in decision tree.

3. Undo (Backtrack)

Pop item from path state so next branch evaluates clean state!

Subsets vs Permutations vs Combinations

Subsets
Decision at each element:
Take or Skip
Generates 2^N subsets
Permutations
Order matters!
Choose unused elements
Generates N! permutations
Combinations
Order does NOT matter!
Use start index to avoid
duplicates like [1,2] & [2,1]
Visual Memory Rule
CHOOSE  →  EXPLORE  →  UNDO
Duplicates  →  Sort array first + skip same-level choices (i > start && nums[i] == nums[i-1])
Pruning     →  Stop early when sum > target or board rule fails

💡 Golden Rule: "Make one choice, explore it fully, undo it, then try the next choice."

Common Interview Mistakes

1. Forgetting to Undo State

Adding to path but forgetting path = path[:len(path)-1] leaks state into parallel branches.

2. Saving Same Slice in Go

Appending path directly to results in Go without copy causes all saved answers to mutate!

3. No Pruning Guard

Exploring impossible paths (e.g. sum > target) causes TLE (Time Limit Exceeded) on $O(2^N)$ search spaces.

4. Duplicate Answer Combinations

For inputs with duplicate elements, sort first and skip same-level duplicates (if i > start && nums[i] == nums[i-1] continue).

Interview Rules

  1. 1. Need all possibilities? → Backtracking
  2. 2. Subsets? → Take / Skip binary decisions
  3. 3. Permutations? → Choose unused elements (visited set)
  4. 4. Combinations? → Start index avoids order duplicates
  5. 5. Board placement (N-Queens, Sudoku)? → Backtracking
  6. 6. Grid word search? → DFS + Backtracking
  7. 7. Duplicate inputs? → Sort first + skip same-level duplicates
  8. 8. Overall ComplexityO(2^N) or O(N!) time complexity

Small Rules

  1. Rule 1: Backtracking = Recursion + State Undo.
  2. Rule 2: You MUST undo state modifications after returning from recursive call.
  3. Rule 3: Prune invalid branches early to avoid TLE.
  4. Rule 4: Make explicit slice copies before appending path to results in Go.
  5. Rule 5: Always track current path, index, used items, and board state explicitly.

Production Thinking

Cloud Infra Configuration SearchSearch region/instance/storage combinations satisfying budget constraints

Employee Shift SchedulingAssign workers to shifts, backtrack on overlap conflict

Room & Resource AllocationAssign meeting rooms and resources with pruning for capacity limits

State Space PruningPrune invalid branch states early in search engines and constraint solvers

Remember This

Choose              → make decision
Explore             → recurse
Invalid?            → stop
Complete?           → save answer (copy slice!)
Undo                → restore state
Then                → next choice

💡 Golden Rule: "Make one choice, explore it fully, undo it, then try the next choice."