Browse Curriculum

The Backtracking Pattern

Build a candidate solution one choice at a time. Recurse after each choice, and if the branch cannot lead to a valid answer, undo the choice and try the next. The undo step is what separates backtracking from plain recursion.

6
Interactive problems
1
Free to open

How to recognise a backtracking problem

The problem asks for all permutations, all subsets, all combinations, or all ways of doing something — or it is a constraint puzzle like N-Queens or Sudoku. "Find every…" means backtracking.

Time and space complexity

Exponential by nature — O(2ⁿ) for subsets, O(n!) for permutations. Pruning invalid branches early is the only meaningful optimisation.

Backtracking practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.


Related patterns and concepts

The underlying technique is covered from first principles in the backtracking lesson in the DSA visualizer curriculum. Backtracking is one of the 16 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.