Skip to content
Data Structures & Algorithmsadvanced · 55 min

Backtracking

Prerequisites: Dynamic Programming

Systematic, depth-first exploration of all candidate solutions, abandoning a path the moment it can't lead to a valid answer. Powers permutations, combinations, N-Queens, Sudoku, and word search.

The template

Choose → explore → un-choose. At each step you make a choice, recurse, then undo the choice before trying the next. A 'prune' check skips branches that already violate constraints, which is what makes backtracking tractable despite exploring a combinatorial space.

Recognising it

Backtracking fits 'generate all/return any valid configuration' problems: subsets, permutations, partitions, placing queens, filling a grid. Complexity is usually exponential in the worst case, so pruning early and ordering choices well matter.

Resources

Practice & test yourself

Take the quiz →

Code challenges