Backtracking
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Backtracking builds an answer one choice at a time, and as soon as a choice leads to a dead end it undoes the last choice and tries another. It avoids exploring huge numbers of hopeless combinations.
Practical use cases
- Web app: Sudoku solver in a puzzle website. A puzzle page offers a "solve it for me" button. The solver fills a cell with a digit, moves on, and when a row breaks the rules it steps back and changes the previous digit. Dead ends are abandoned at the first conflict, so the Sudoku is solved in a blink instead of trying every combination.
- Web app: College timetable generator. A school portal must place 40 classes into rooms and periods without clashes. The generator places one class at a time, and when no room fits the next class, it moves the previous one and tries again. Administrators get a clash-free timetable instead of fixing hundreds of conflicts by hand.
- Web app: Regex-based form validation. Many regular expressions in PHP and JavaScript work by backtracking: they try one way of matching and step back when it fails. When a pattern allows too many ways to match, the dead ends pile up and the page can hang, so knowing this helps you write safer patterns.
- System: Puzzle and constraint solvers. Constraint solvers for scheduling, crossword building and configuration tools use the same try, check, undo cycle. Because bad partial answers are dropped early, these tools can solve problems that would otherwise take years.
The story: The Piggy Bank Puzzle
Mira cracked open her piggy bank and found only ₹2, ₹3 and ₹5 coins, but plenty of each. Grandpa Bhaskar set a challenge: "Show me every way to pay exactly ₹7 using those coins."
Mira began dropping coins into a bag: 2, then 2, then 2 again, total 6. Need 1 more, but no coin is that small. Stuck! Did she throw everything away? No. She took the last coin out and tried a 3 instead: 2+2+3 = 7. A solution! She wrote it down, then took that coin out too and kept exploring.
Notice her rhythm: choose a coin, go deeper, and if it fails (or succeeds), un-choose it and try the next coin. She also learned to stop early: if the bag already holds more than 7, don’t bother adding anything else.
That is backtracking. The smell: "find all combinations / permutations / subsets", "generate every valid...", "place N queens", "solve the Sudoku". You are searching a tree of choices and need to step back after each attempt. Add pruning to cut off hopeless branches early.
How to spot this problem, and where you need it
You must find an arrangement that satisfies several rules, and the number of possibilities is far too large to list, but you can tell early that a partial arrangement is already wrong.
Signs you need it
- The task says "find all ways", "place without conflict", "generate all valid arrangements" or "solve the puzzle".
- Every step has a few options, and some choices can be rejected immediately because they break a rule.
- A brute-force version that creates every full combination first takes forever.
Where to use it in a project
- Timetable, seating and roster generators that must avoid clashes between people or rooms.
- Puzzle, game and crossword solvers that try a move and undo it on failure.
- Generating valid combinations, such as coupon codes or product bundles under rules.
The solution
Build the answer step by step. At each step, loop over the possible choices, and skip any that already break a rule. Make a valid choice, then recurse to fill in the next step. If the recursion returns with no solution, undo the choice (the backtrack) and try the next. When all steps are filled, record or return the answer.
Payoff: Before: trillions of full combinations tested. After: most branches cut early, and a Sudoku solves in milliseconds.
Explain it like I am 8
You are in a maze. At each fork you pick a path. If you hit a wall you walk back to the last fork and take another path. You never start the maze again from the beginning; you just undo the last choice.
How it works, step by step
- Spot the clue: "all possible ways", "every valid arrangement" or "does any arrangement work?" over a series of choices.
- Choose: add one option to your current path.
- Explore: recurse to make the next choice with what is left. If the path is complete and valid, save a copy.
- Un-choose: remove that option again (
array_pop/pop()) so the next sibling starts from a clean path. - Prune: stop a branch the moment it cannot possibly work (sum already too big, queen attacked). Sorting the options lets you
breakearly.
The code in four languages
PHP
<?php
// Classic: "Combination Sum": every way to reach the target, coins reusable.
function combinationSum(array $coins, int $target): array {
sort($coins); // sorted, so we can stop early with break
$answers = [];
$bag = [];
$walk = function (int $start, int $remaining) use (&$walk, &$answers, &$bag, $coins) {
if ($remaining === 0) {
$answers[] = $bag; // a full solution: save a COPY of the bag
return;
}
for ($i = $start; $i < count($coins); $i++) {
if ($coins[$i] > $remaining) break; // pruning: this and larger coins cannot fit
$bag[] = $coins[$i]; // 1. choose
$walk($i, $remaining - $coins[$i]); // 2. explore (same coin allowed again)
array_pop($bag); // 3. un-choose (backtrack)
}
};
$walk(0, $target);
return $answers;
}
echo json_encode(combinationSum([2, 3, 5], 7)), "
"; // [[2,2,3],[2,5]]
echo json_encode(combinationSum([4], 6)), "
"; // [] (no way)JavaScript
// Classic: "Combination Sum": every way to reach the target, coins reusable.
function combinationSum(coins, target) {
coins = [...coins].sort((a, b) => a - b); // sorted, so we can stop early with break
const answers = [];
const bag = [];
function walk(start, remaining) {
if (remaining === 0) {
answers.push([...bag]); // a full solution: save a COPY of the bag
return;
}
for (let i = start; i < coins.length; i++) {
if (coins[i] > remaining) break; // pruning: this and larger coins cannot fit
bag.push(coins[i]); // 1. choose
walk(i, remaining - coins[i]); // 2. explore (same coin allowed again)
bag.pop(); // 3. un-choose (backtrack)
}
}
walk(0, target);
return answers;
}
console.log(JSON.stringify(combinationSum([2, 3, 5], 7))); // [[2,2,3],[2,5]]
console.log(JSON.stringify(combinationSum([4], 6))); // [] (no way)Java
import java.util.*;
public class Main {
static int[] coins;
static List<List<Integer>> answers;
static List<Integer> bag;
// Classic: "Combination Sum": every way to reach the target, coins reusable.
static List<List<Integer>> combinationSum(int[] input, int target) {
coins = input.clone();
Arrays.sort(coins); // sorted, so we can stop early with break
answers = new ArrayList<>();
bag = new ArrayList<>();
walk(0, target);
return answers;
}
static void walk(int start, int remaining) {
if (remaining == 0) {
answers.add(new ArrayList<>(bag)); // a full solution: save a COPY of the bag
return;
}
for (int i = start; i < coins.length; i++) {
if (coins[i] > remaining) break; // pruning: this and larger coins cannot fit
bag.add(coins[i]); // 1. choose
walk(i, remaining - coins[i]); // 2. explore (same coin allowed again)
bag.remove(bag.size() - 1); // 3. un-choose (backtrack)
}
}
public static void main(String[] args) {
System.out.println(combinationSum(new int[]{2, 3, 5}, 7)); // [[2, 2, 3], [2, 5]]
System.out.println(combinationSum(new int[]{4}, 6)); // [] (no way)
}
}Go
package main
import (
"fmt"
"slices"
)
// combinationSum finds every way to reach the target, coins reusable.
func combinationSum(input []int, target int) [][]int {
coins := slices.Clone(input)
slices.Sort(coins) // sorted, so we can stop early with break
answers := [][]int{}
var bag []int
var walk func(start, remaining int)
walk = func(start, remaining int) {
if remaining == 0 {
answers = append(answers, slices.Clone(bag)) // a full solution: save a COPY of the bag
return
}
for i := start; i < len(coins); i++ {
if coins[i] > remaining {
break // pruning: this and larger coins cannot fit
}
bag = append(bag, coins[i]) // 1. choose
walk(i, remaining-coins[i]) // 2. explore (same coin allowed again)
bag = bag[:len(bag)-1] // 3. un-choose (backtrack)
}
}
walk(0, target)
return answers
}
func main() {
fmt.Println(combinationSum([]int{2, 3, 5}, 7)) // [[2 2 3] [2 5]]
fmt.Println(combinationSum([]int{4}, 6)) // [] (no way)
}Time: O(branches^depth), exponential · Extra space: O(depth). Backtracking explores a tree of choices, so it can be big; pruning cuts away whole branches.
Watch out for
- Saving the bag itself instead of a copy. In JS,
answers.push(bag)stores a reference that later changes to empty. - Forgetting the un-choose step, so choices pile up and later branches start dirty.
- No pruning at all, which makes a solvable puzzle take forever.
Quick check
- Which phrase smells like backtracking?
- "generate all valid combinations"
- "maximum sum of a subarray"
- "shortest path in a graph"
- "is the list sorted"
- What is the three-beat rhythm of backtracking?
- Sort, search, return
- Split, solve, merge
- Choose, explore, un-choose
- Push, pop, peek
- What does pruning do?
- Sorts the answers
- Stops exploring a branch that cannot succeed
- Removes duplicates at the end
- Makes recursion iterative