Chapter 14 - Backtracking
Choose, explore, undo. Backtracking builds every candidate one step at a time and gives up as soon as a path cannot succeed.
This page is the entry point of chapter 14 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
A backtracking function adds one element to the current candidate, calls itself to go deeper, then removes the element to try the next option. Without pruning, it enumerates everything; with good pruning (a queen already attacked, a sum already too large), whole branches are skipped. The result size is often exponential, so the goal is to avoid useless work, not to reach a polynomial time.
When to reach for it
- “All” permutations, subsets or combinations.
- Placement puzzles: N queens, Sudoku.
- Building strings from choices, like phone keypad letters.
In Rust
- Pass the current candidate as
&mut Vec<T>:pushbefore the recursive call,popafter it. - Push
candidate.clone()into the results: the candidate itself keeps changing. - A
Vec<bool>of used elements is cheaper than searching the candidate for every check.
Problems in this chapter
- p298 - Find All Permutations: Find All Permutations (Backtracking), solved in Rust. Return all permutations of a given array of unique i32. They can be returned in any order.
- p302 - Find All Subsets: Find All Subsets (Backtracking) solved in Rust: return all the possible subsets of a given set of i32, in any order.
- p305 - N Queens: N Queens (Backtracking) solved in Rust: count the ways to place n queens on an n x n chessboard so that no two queens attack each other.
- bonus123 - Combinations of a Sum: Combinations of a Sum (Backtracking), solved in Rust. Given an integer array and a target value. Find all unique combinations in the array where the numbers…
- bonus128 - Phone Keypad Combinations: Phone Keypad Combinations (Backtracking), solved in Rust. You are given a string containing digits from 2 to 9 inclusive. Each digit maps to a set of letters.
Other chapters
All the chapters, with every problem, are listed on the series page.