Skip to main content

Coding interview pattern

Backtracking

Build candidates incrementally and abandon a partial solution the moment it cannot work.

The idea

How the backtracking pattern works

Backtracking is a refined brute force for problems that ask you to enumerate or find configurations satisfying constraints: all permutations, all subsets, all valid board placements. It builds a candidate one decision at a time, and the instant a partial candidate violates a constraint it prunes that entire branch and backtracks, undoing the last decision before trying the next. The pruning is what separates it from blind exhaustive search.

The canonical structure is a recursive function that takes the current partial solution, tries each available choice, recurses, and then undoes the choice (the explicit backtrack step). Choose, explore, un-choose. Getting the un-choose right is the most common source of bugs: every mutation made before the recursive call must be reverted after it, or state leaks across branches.

Backtracking is inherently exponential because the search space is exponential, so the interview signal is not avoiding that, it is pruning aggressively and structuring the recursion cleanly. Strong candidates identify the earliest possible point to reject a branch (for N-Queens, checking column and diagonal conflicts before placing) so the constant factor stays manageable.

Recognition

When to reach for it

  • The problem asks for all valid configurations, or to find one that satisfies constraints.
  • You are generating permutations, combinations, subsets, or partitions.
  • Choices are made sequentially and a partial choice can be validated early.
  • The search space is exponential but heavy pruning is possible.

Cost

Time & space complexity

OperationTimeSpace
SubsetsO(2^n)O(n) recursion
PermutationsO(n!)O(n) recursion
N-QueensO(n!) worst, far less with pruningO(n)

Worked example

Walkthrough: Generate all subsets

  1. 1Recurse with a start index and the current partial subset.
  2. 2At each call, record the current subset as one valid answer.
  3. 3For each index from start to the end, choose that element (append it), recurse with the next start index, then un-choose (pop it).
  4. 4Advancing the start index each level prevents generating the same subset in different orders.
  5. 5The choose-recurse-unchoose triple is the heartbeat of every backtracking solution.

Translatable skeleton

The shape in pseudocode

Language-agnostic on purpose. Translate it to your language of choice.

Code
def bt(state, start): record(state); for i in range(start, n): choose(i); bt(state, i + 1); unchoose(i)

Practice

Curated problem set

Work these in order, easy to hard. Each is chosen to drill a different facet of the pattern.

ProblemLevelWhy it fits
SubsetsMediumThe cleanest introduction to choose/unchoose.
PermutationsMediumTrack used elements; n! leaves.
Combination SumMediumReuse allowed; prune when the sum exceeds target.
Word SearchMediumBacktrack over grid cells with visited marks.
Palindrome PartitioningMediumCut at every valid palindrome prefix.
N-QueensHardPrune on column and diagonal conflicts early.

Avoid these

Common pitfalls

  • Forgetting the un-choose step, so state leaks across branches.
  • Recording references to a mutable structure instead of a copy.
  • Weak pruning, turning a tractable search into a timeout.
  • Generating duplicates when the input has repeated elements.

In the interview

How to communicate it live

Recognising the pattern is half the score; saying the right things out loud is the other half. These are the sentences that earn the signal.

1

Say the heartbeat aloud, choose, recurse, un-choose, and point out that forgetting the un-choose is the classic bug; verbalising it proves you know the pitfall before you hit it.

2

Identify the earliest point you can reject a partial candidate and prune there, then explain that aggressive pruning is what keeps an exponential search practical; this is the main signal on backtracking.

3

When recording an answer, mention that you push a copy of the partial state, not a reference, so later mutations do not corrupt results already collected.

Also searched as

backtracking interview - permutations and combinations - constraint search

Last reviewed by the site editor: June 2026

Practise these patterns on AlgoExpert
Recommended
200+ video-explained coding interview questions organised by the patterns covered on this page, with timed practice and solution walkthroughs.
Start practising

An external resource we recommend. AlgoExpert is not affiliated with us and we earn nothing from this link.

Sources

  1. Backtracking (Chapter 2, Algorithms) Jeff Erickson, University of Illinois Urbana-Champaign
  2. Competitive Programmer's Handbook: complete search, backtracking and pruning (Chapter 5) Antti Laaksonen, CSES
  3. Backtracking Wikipedia

Round out your prep

See all coding patterns, the coding questions for your role, and the behavioral round.