Backtracking

Systematically explore every candidate by choosing, recursing and un-choosing — with pruning to make it fast enough.

Intermediate 2 min readLesson 10 of 18 Interview Q&A

Backtracking builds solutions one decision at a time. After each choice it recurses; if the partial solution can't lead anywhere valid, it undoes the last choice ("backtracks") and tries the next option. It's a depth-first search over the tree of decisions.

[1,2,3][1,2][1,3,2][1,3][1][2,1][2,3][2][3,1][3,2][3][]
Decision tree for permutations of [1,2,3] (partially expanded). Each leaf is a complete permutation.

The template

backtrack(state):
    if state is a complete solution: record it; return
    for each choice available from state:
        if choice is invalid: continue          ← pruning
        make the choice                          ← choose
        backtrack(new state)                     ← explore
        undo the choice                          ← un-choose

Every backtracking problem is this template; only the choices, validity check and completion test differ.

Permutations, combinations, subsets

// Permutations of distinct numbers: n! results
List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    backtrack(nums, new ArrayList<>(), new boolean[nums.length], res);
    return res;
}
void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> res) {
    if (path.size() == nums.length) { res.add(new ArrayList<>(path)); return; }   // copy!
    for (int i = 0; i < nums.length; i++) {
        if (used[i]) continue;
        used[i] = true; path.add(nums[i]);           // choose
        backtrack(nums, path, used, res);             // explore
        path.remove(path.size() - 1); used[i] = false; // un-choose
    }
}

// Combinations: choose k of 1..n
void combine(int start, int n, int k, List<Integer> path, List<List<Integer>> res) {
    if (path.size() == k) { res.add(new ArrayList<>(path)); return; }
    for (int i = start; i <= n - (k - path.size()) + 1; i++) {   // prune: enough numbers left
        path.add(i);
        combine(i + 1, n, k, path, res);
        path.remove(path.size() - 1);
    }
}
ProblemCountTime
Subsets2ⁿO(n · 2ⁿ)
Permutationsn!O(n · n!)
Combinations C(n, k)n! / (k!(n−k)!)O(k · C(n, k))

Duplicates in the input? Sort first, then skip a choice equal to the previous one at the same depth: if (i > start && nums[i] == nums[i-1]) continue;.

Constraint problems: N-Queens and Sudoku

Place N queens so none attack each other. Choose a column for each row; prune any column or diagonal already attacked. Using sets (or bitmasks) for columns and both diagonals makes each validity check O(1).

int totalNQueens(int n) { return place(0, n, new boolean[n], new boolean[2 * n], new boolean[2 * n]); }
int place(int r, int n, boolean[] cols, boolean[] d1, boolean[] d2) {
    if (r == n) return 1;
    int count = 0;
    for (int c = 0; c < n; c++) {
        if (cols[c] || d1[r + c] || d2[r - c + n]) continue;   // attacked → prune
        cols[c] = d1[r + c] = d2[r - c + n] = true;
        count += place(r + 1, n, cols, d1, d2);
        cols[c] = d1[r + c] = d2[r - c + n] = false;
    }
    return count;
}

Making backtracking fast

  • Prune early — reject partial solutions as soon as a constraint is violated (or a bound shows they can't beat the best so far: branch and bound).
  • Order choices well — try the most constrained variable first (Sudoku: the cell with the fewest candidates).
  • Use O(1) validity checks — sets, boolean arrays or bitmasks instead of rescanning.
  • Memoize if identical sub-states recur — then it's really DP.
Key takeaways
  • Backtracking = DFS over a decision tree: choose → explore → un-choose.
  • Record copies of the current path.
  • Exponential by nature; pruning and good ordering make it practical.
  • Sort + skip equal neighbours to avoid duplicate results.
Interview questions
QGenerate all valid combinations of n pairs of parentheses.medium

Backtrack with counts of open and close used: add '(' if open < n; add ')' if close < open. Complete when the length is 2n. The pruning guarantees every leaf is valid; the count is the n-th Catalan number.

QWord search: does a word exist in a grid of letters?medium

DFS from each cell matching the first letter; at each step move to a neighbour matching the next letter, temporarily marking the cell visited (e.g. overwrite it with '#') and restoring it on backtrack. O(cells · 4ᴸ) worst case.