Skip to main content

πŸ”™ Backtracking

One-line summary: Explore all possible solutions by incrementally building candidates and abandoning ("backtracking") as soon as a constraint is violated.


Diagram​

Backtracking Flow Backtracking GIF

Concept​

  1. Choose β€” pick a candidate.
  2. Explore β€” recurse with that choice.
  3. Unchoose β€” undo the choice, try next.

Prune early: if current state already violates a constraint, skip the subtree.

Time: O(b^d) where b = branching factor, d = depth. Space: O(d) for the call stack.


Common Patterns​

Subsets​

function subsets(nums) {
const result = [];
function bt(start, curr) {
result.push([...curr]);
for (let i = start; i < nums.length; i++) {
curr.push(nums[i]);
bt(i + 1, curr);
curr.pop();
}
}
bt(0, []);
return result;
}

Permutations​

function permute(nums) {
const result = [],
used = new Array(nums.length).fill(false);
function bt(curr) {
if (curr.length === nums.length) {
result.push([...curr]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (!used[i]) {
used[i] = true;
curr.push(nums[i]);
bt(curr);
curr.pop();
used[i] = false;
}
}
}
bt([]);
return result;
}

Constraint Satisfaction (N-Queens skeleton)​

function solve(row, board, result) {
if (row === board.length) {
result.push(board.map((r) => r.join('')));
return;
}
for (let col = 0; col < board.length; col++) {
if (isValid(board, row, col)) {
board[row][col] = 'Q';
solve(row + 1, board, result);
board[row][col] = '.'; // unchoose
}
}
}

Pitfalls​

  • Not spreading [...curr] before pushing to result β€” captures reference
  • Missing pruning β€” O(b^d) blows up without early constraint checks
  • Duplicate handling: sort input and skip duplicate values at same depth level

Practice Problems​

ProblemDifficultySolution
LC 78 β€” SubsetsMedium
LC 46 β€” PermutationsMedium
LC 39 β€” Combination SumMedium
LC 22 β€” Generate ParenthesesMedium
LC 51 β€” N-QueensHard
LC 37 β€” Sudoku SolverHard
LC 131 β€” Palindrome PartitioningMedium
LC 79 β€” Word SearchMedium
LC 47 β€” Permutations IIMedium
LC 52 β€” N-Queens IIHard
LC 212 β€” Word Search IIHard
LC 140 β€” Word Break IIHard
LC 282 β€” Expression Add OperatorsHard
LC 301 β€” Remove Invalid ParenthesesHard
LC 473 β€” Matchsticks to SquareHard
LC 679 β€” 24 GameHard
LC 996 β€” Number of Squareful ArraysHard
CC β€” N-Queens Problem (NQUEENS)Hard
CC β€” Sudoku Solver (SUDOKU)Hard
CC β€” Graph Coloring (GRAPHCOL)Hard
LC 90 β€” Subsets IIMedium
LC 40 β€” Combination Sum IIMedium
LC 77 β€” CombinationsMedium
LC 216 β€” Combination Sum IIIMedium
LC 93 β€” Restore IP AddressesMedium
LC 17 β€” Letter Combinations of a Phone NumberMedium
LC 526 β€” Beautiful ArrangementMedium
LC 698 β€” Partition to K Equal Sum SubsetsMedium
LC 784 β€” Letter Case PermutationMedium
LC 1079 β€” Letter Tile PossibilitiesMedium
CC β€” Subset Generation (SUBGEN)Medium
CC β€” Permutation Generation (PERMGEN)Medium
CC β€” Combination Problems (COMBPROB)Medium

← Back to Home Β· Β© sparshjaswal