Browse curriculum

Backtracking

Backtracking Interview Questions: 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. Below are the backtracking interview questions from LeetCode, each with a step-by-step visual solution.

17

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 interview questions: 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
PermutationsMediumΩ(n · n!)Θ(n · n!)O(n · n!)O(n)
Permutations IIMediumΩ(n · n!)Θ(n · n!)O(n · n!)O(n)
CombinationsMediumΩ(k · C(n, k))Θ(k · C(n, k))O(k · C(n, k))O(k)
Letter Case PermutationMediumΩ(n · 2^k)Θ(n · 2^k)O(n · 2^k)O(n)
N-QueensHardΩ(n!)Θ(n!)O(n!)O(n)
Sudoku SolverHardΩ(m)O(9^m)O(9^m)O(m)
Subsets IIMediumΩ(n log n)Θ(n · 2^n)O(n · 2^n)O(n)
Combination SumMediumO(n log n)O(n^(T/m + 1))O(n^(T/m + 1))O(T/m) depth
Combination Sum IIMediumΩ(n log n)Θ(n · 2^n)O(n · 2^n)O(n)
Combination Sum IIIMediumΩ(1)Θ(C(9, k) · k)O(C(9, k) · k)O(k)
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
Letter Combinations of a Phone NumberMediumΩ(3^n · n)Θ(4^n · n)O(4^n · n)O(n)
Palindrome PartitioningMediumΩ(n²)Θ(n · 2^n)O(n · 2^n)O(n)
Curriculum

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

Directory

Every other coding interview pattern