Browse curriculum

Backtracking

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

Recognise

How do you 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.

Complexity

What is the time complexity of the backtracking pattern?

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

Problems

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++.

Complexity

Backtracking problems by difficulty and complexity

The difficulty, running time and extra space of every backtracking solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to BacktrackingMediumΩ(n × 2ⁿ)Θ(n × 2ⁿ)O(n × 2ⁿ)O(n) path, O(n × 2ⁿ) output
Solution Space TreesMediumΩ(n × 2ⁿ)Θ(n × 2ⁿ)O(n × 2ⁿ)O(n) depth, O(n × 2ⁿ) output
Subsets (Power Set)MediumΩ(n × 2ⁿ)Θ(n × 2ⁿ)O(n × 2ⁿ)O(n) depth, O(n × 2ⁿ) output
Combination SumMediumO(n log n)O(n^(T/m + 1))O(n^(T/m + 1))O(T/m) depth
Generate ParenthesesMediumΩ(4ⁿ / √n)Θ(4ⁿ / √n)O(4ⁿ / √n)O(n) depth, O(4ⁿ / √n) output
Word SearchMediumO(m × n)O(m × n × 3ᴸ)O(m × n × 3ᴸ)O(L) stack
Curriculum

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

Directory

Every other coding interview pattern