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.SubsetsBinary choice: Take or Skip at indexmedium
- 2.Subsets IISort array + skip duplicate adjacent choicesmedium
- 3.PermutationsUnused elements choice + visited boolean arraymedium
- 4.Permutations IISort array + skip duplicate choices at same depthmedium
- 5.Combination SumReusable element choice (recurse with same index)medium
- 6.Combination Sum IISort + single-use element with duplicate skipmedium
- 7.Generate ParenthesesTrack open & close bracket countsmedium
- 8.Letter Combinations of a Phone NumberDigit mapping backtracking choicemedium
- 9.Word SearchGrid DFS 4-directional search + visited restoremedium
- 10.Palindrome PartitioningSub-string palindrome check + partition backtrackmedium
- 11.N-QueensRow-by-row queen placement + diagonal conflict pruninghard
- 12.N-Queens IICount total valid board configurationshard
- 13.Sudoku Solver9x9 grid 1-9 digit trial + row/col/box validationhard
- 14.Restore IP AddressesValid 0-255 segment partitioning recursionmedium
- 15.Combination Sum IIIK numbers summing to N using 1-9 without duplicatesmedium
- 16.Word Search IITrie Data Structure + Grid Backtracking DFShard
Also Important
9 more questions worth practicing.
- 17.CombinationsN choose K start index recursionmedium
- 18.Beautiful ArrangementDivisibility check backtracking pruningmedium
- 19.Matchsticks to Square4-side sum partitioning + sort descendingmedium
- 20.Partition to K Equal Sum SubsetsK subset sum buckets + pruningmedium
- 21.Letter Tile PossibilitiesCharacter count frequency map backtrackingmedium
- 22.Split a String Into the Max Number of Unique SubstringsHashSet seen substrings backtrackingmedium
- 23.Maximum Length of a Concatenated String with Unique CharactersBitmask char set unique concatenationmedium
- 24.Rat in a Maze4-directional grid maze path searchmedium
- 25.Graph Coloring ProblemK-color assignment + vertex neighbor checkmedium
How to Think
- Need all possible answers?Backtracking
- Need try different choices?Choose, Explore, Undo
- Need permutations / subsets / combinations?Backtracking
- Need place things with rules (N-Queens, Sudoku)?Backtracking
- Need search a path in grid?DFS + Backtracking
- 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
Make decision: Add item/digit/board position to current path state.
Recurse to next step or next index in decision tree.
Pop item from path state so next branch evaluates clean state!
Subsets vs Permutations vs Combinations
Decision at each element:
Take or Skip
Generates 2^N subsetsOrder matters!
Choose unused elements
Generates N! permutationsOrder does NOT matter!
Use start index to avoid
duplicates like [1,2] & [2,1]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
Adding to path but forgetting path = path[:len(path)-1] leaks state into parallel branches.
Appending path directly to results in Go without copy causes all saved answers to mutate!
Exploring impossible paths (e.g. sum > target) causes TLE (Time Limit Exceeded) on $O(2^N)$ search spaces.
For inputs with duplicate elements, sort first and skip same-level duplicates (if i > start && nums[i] == nums[i-1] continue).
Interview Rules
- 1. Need all possibilities? → Backtracking
- 2. Subsets? → Take / Skip binary decisions
- 3. Permutations? → Choose unused elements (visited set)
- 4. Combinations? → Start index avoids order duplicates
- 5. Board placement (N-Queens, Sudoku)? → Backtracking
- 6. Grid word search? → DFS + Backtracking
- 7. Duplicate inputs? → Sort first + skip same-level duplicates
- 8. Overall Complexity →
O(2^N) or O(N!)time complexity
Small Rules
- Rule 1: Backtracking = Recursion + State Undo.
- Rule 2: You MUST undo state modifications after returning from recursive call.
- Rule 3: Prune invalid branches early to avoid TLE.
- Rule 4: Make explicit slice copies before appending path to results in Go.
- Rule 5: Always track current path, index, used items, and board state explicitly.
Production Thinking
Cloud Infra Configuration Search → Search region/instance/storage combinations satisfying budget constraints
Employee Shift Scheduling → Assign workers to shifts, backtrack on overlap conflict
Room & Resource Allocation → Assign meeting rooms and resources with pruning for capacity limits
State Space Pruning → Prune 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."