undoBacktracking

Backtracking: when to spot it, explain it, and practice it

Backtracking is a disciplined way to explore decision trees. Good answers do not just recurse; they define the current path, remaining choices, stopping condition, and pruning opportunities precisely.

Pattern coverage

55+

Best first move

Define what the path means.

Common failure point

Forgetting to undo state and leaking one branch into another.

When this pattern should come to mind

The problem asks for all combinations, permutations, subsets, or valid constructions.
A decision tree exists and each level chooses one item or state.
The result space can be huge, so pruning matters.

Checklist before you code

Define what the path means.
Define what counts as a complete solution.
List which choices remain available at each depth.
Undo every state mutation before the next branch.

The solving flow that works well in interviews

1

Model the decision tree explicitly.

2

Choose the next candidate set for the current depth.

3

Check whether a choice is valid before recursing.

4

Apply the choice, recurse, then undo it exactly once.

5

Prune branches early if they can never reach a valid solution.

Common variants

Permutation search

Each level chooses one unused item.

Combination search

Use an index to avoid revisiting earlier choices.

Constraint backtracking

Validity checks and pruning dominate performance.

Template preview

PythonPublic preview
def backtrack(path):
    if complete(path):
        answer.append(path[:])
        return
    for choice in choices(path):
        if not valid(choice, path):
            continue
        path.append(choice)
        backtrack(path)
        path.pop()

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Forgetting to undo state and leaking one branch into another.

warning

Not copying the path when saving an answer.

warning

Allowing duplicate combinations due to poor index handling.

warning

Skipping pruning opportunities and timing out.

Recommended practice path

1

Start with subsets and permutations.

2

Then solve combination sum and restore IP style problems.

3

Add board search questions like word search.

4

Finish with N-Queens and other strong-pruning problems.

Backtracking Pattern Guide | LeetCode Interview Prep - Interview AiBox