What is Backtracking?
Patterns·6 min·Python code
Backtracking solves problems by exploring a tree of choices depth first. When a path hits a dead end, code undoes its last choice and tries another, so no invalid partial solution survives.
How Backtracking Builds and Undoes Choices
Imagine a maze where you unspool a thread as you walk. At every junction you choose a direction and keep going. At a wall, you follow your thread back to the last junction and try another direction.
Backtracking works the same way in code. Make a choice and recurse to explore its consequences. If that path fails, undo the choice and try another.
Blind trial and error wastes time, but smart code drops a path the instant that path is provably hopeless. If one queen placement already puts two queens on a diagonal, there is no point filling the rest of the board. That early exit defines backtracking.
How the State Space Tree and Pruning Work
Backtracking searches a state space tree with depth first search. Every node is a partial solution and every edge is one more choice, like a number in a permutation, a queen's column or a digit in a Sudoku cell.
Your recursive function tries all valid choices at one level and restores state after the call, so every new choice starts clean. When a partial solution is finished you record it. When no choice is valid the call returns and control flows back up the tree.
Two moves define every backtracking function. Constraint checks ask whether a choice is still valid, and undo removes the choice before another try. Pruning happens in the constraint check, so a tighter and earlier check skips more of the tree.
One Backtracking Template for Many Problems
Nearly every backtracking solution has the same shape. Its base case records a finished solution and its loop walks the candidate choices, with a choose, recurse, undo trio inside. Learn that skeleton once and permutations, subsets, combination sum, N-Queens, word search and Sudoku become variations.
Candidate generation is where problems differ. Subsets decide include or skip for every element, permutations select any unused element and grid problems branch into neighbouring cells. Recursion, base case and undo stay the same.
Practise the template on CodeStory's backtracking practice problems.
Backtracking Code Example in Python
def permutations(nums):
result = []
def backtrack(path, remaining):
if not remaining: # finished solution
result.append(path[:]) # store a COPY, not the shared list
return
for i in range(len(remaining)):
path.append(remaining[i]) # choose
backtrack(path, remaining[:i] + remaining[i + 1:]) # explore
path.pop() # undo
backtrack([], nums)
return result
Edit the permutation code in CodeStory's browser IDE, free on the platform. Open the CodeStory App
Backtracking Time and Space Complexity
| Time | O(n · n!) for permutations, exponential in general |
|---|---|
| Space | O(n) recursion depth, plus the space to store results |
Backtracking costs as many steps as it visits nodes in a state space tree, so cost depends on the problem. Subsets take O(2^n) and N-Queens takes roughly O(n!). Strong pruning cuts real work a lot but does not change the Big O worst case.
When to Use Backtracking
- Listing all permutations, combinations or subsets of a set.
- Constraint puzzles like N-Queens, Sudoku or crossword filling.
- Grid search where you follow a path and then retreat, like word search.
- Partition and combination sum problems that need every valid arrangement.
Mistakes to Avoid
- Forgetting the undo step, so state leaks between branches and results go wrong.
- Storing a reference to the mutable path instead of a copy, so every saved result points to one list that ends up empty.
- Weak or missing pruning and no visited or index guard, which explores the full tree, revisits states and times out on larger inputs.
Backtracking FAQs
Is backtracking hard to learn?
No, once the pattern clicks. Most people forget to undo a choice before trying the next. Learn the choose, recurse and undo template and practise five or six classic problems, and backtracking stops feeling mysterious.
What is the time complexity of backtracking?
Cost depends on the problem and is exponential in the worst case, because code can explore a large tree of choices. Permutations cost O(n·n!), subsets cost O(2^n) and N-Queens costs roughly O(n!). Early pruning cuts real work but leaves the Big O upper bound unchanged.
What is the difference between backtracking and DFS?
Backtracking is depth first search over a tree of partial solutions, with one addition. It undoes a choice when a branch fails so the shared state stays correct. Every backtracking algorithm is a DFS, but a plain DFS only visits nodes and does not build or unbuild a candidate.
When should I use backtracking instead of dynamic programming?
Use backtracking when you need actual arrangements, like all permutations, every valid board or a path that meets constraints. Use dynamic programming when you need an optimal value or a count and the problem has overlapping subproblems you can cache. If you recompute the same states, switch to DP or memoization.
What does pruning mean in backtracking?
Pruning means abandoning a branch as soon as a constraint check fails. Tighter and earlier checks skip more of the tree.
Why must I copy the path before saving a result?
Undoing choices keeps emptying the path list. Saved references end up pointing at an empty list, so every result needs its own copy.
How do I practise backtracking on CodeStory?
CodeStory groups backtracking problems by pattern, so you can solve permutations, subsets and grid searches back to back, then defend your approach in a spoken mock round.
Related Guides
Guides are step one. In a CodeStory batch you code the template yourself, then defend your choices to an interviewer in a scored mock round.
Talk to a Mentor