Skip to contentKEEP THE CRAFTTHE SANCTUARY

Backtracking

Explore legal decision paths, pruning only impossible completions and restoring mutable state before siblings. Separate enumeration cost, output copies, duplicate choice rules and a decreasing search measure.

1 practice exercise14 interview problems

Recognize it when The output consists of candidate arrangements or combinations, not just one cached aggregate.

Checking your account…

Backtracking Code Labs

Search a Decision Tree

Backtracking explores a tree whose nodes are partial candidates and whose edges are choices. A solution is recorded only when the path satisfies the terminal contract.

Choose Apply Explore Undo

For each choice: apply it to the current path, explore the smaller remaining problem, then undo exactly that mutation. Copy only when recording output; otherwise share one path and restore it before the next sibling.

Trace Apply Explore Undo

Reference
def binary_choice_trace(length):
    events = []
    path = []
    def search():
        if len(path) == length: return
        for choice in (0, 1):
            path.append(choice)
            events.append(["choose", path.copy()])
            search()
            events.append(["undo", path.copy()])
            path.pop()
    search()
    return events
Practice

Implement binary_choice_trace(length). Return ["choose", path] and ["undo", path] events while exploring 0 before 1 to the requested length. Require length to be a nonnegative integer.

Public tests

  • Restore path after every branch

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Apply Explore Undo

def binary_choice_trace(length):
    events = []
    path = []
    def search():
        if len(path) == length: return
        for choice in (0, 1):
            path.append(choice)
            events.append(["choose", path.copy()])
            search()
            events.append(["undo", path.copy()])
            path.pop()
    search()
    return events

Read the Undo Event Before the Actual Pop

Predict the existing event Lab at depth one. The label undo records the path before removal; it is not a snapshot of the already restored path.

Step Executed statement State Why
Apply first choice path.append(choice);events.append(["choose",path.copy()]) path=[0], first event=["choose",[0]] The recorded copy survives later mutations.
Reach requested length if len(path)==length:return child returns with path=[0] The base case stops descent but does not perform the parent undo.
Record and restore events.append(["undo",path.copy()]);path.pop() undo event contains [0], then path=[] The event is taken before pop, so it names the choice being removed.
Explore sibling path.append(choice);events.append(["choose",path.copy()]);search();events.append(["undo",path.copy()]);path.pop() after choice 1: two more events, path=[] Restoration makes the sibling start from the same empty parent state.
Zero length if len(path)==length:return events=[] An already complete empty path needs no choice or undo event.
Print Output
print(binary_choice_trace(1)) [['choose', [0]], ['undo', [0]], ['choose', [1]], ['undo', [1]]]
print(binary_choice_trace(0)) []

In unique_combinations, sorted values enable same-depth duplicate skipping. Moving to index+1 prevents reuse of an input index, while still allowing distinct equal-valued indexes in one combination.

Prune Only with Proof

A prune is correct only when no completion below the current state can succeed. Sort choices to enable duplicate skipping or monotone bounds, and distinguish “skip this duplicate at this depth” from banning a value globally.

Build Unique Combinations

Reference
def unique_combinations(values, width):
    values = sorted(values)
    result = []
    path = []
    def search(start):
        if len(path) == width:
            result.append(path.copy())
            return
        for index in range(start, len(values)):
            if index > start and values[index] == values[index - 1]: continue
            path.append(values[index])
            search(index + 1)
            path.pop()
    search(0)
    return result
Practice

Implement unique_combinations(values, width). Return lexicographically ordered unique combinations of the requested width; each input index is used at most once.

Public tests

  • Skip duplicate choices at one depth

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build Unique Combinations

def unique_combinations(values, width):
    values = sorted(values)
    result = []
    path = []
    def search(start):
        if len(path) == width:
            result.append(path.copy())
            return
        for index in range(start, len(values)):
            if index > start and values[index] == values[index - 1]: continue
            path.append(values[index])
            search(index + 1)
            path.pop()
    search(0)
    return result

Choose Backtracking or Dynamic Programming

Use backtracking when outputs or constraints require enumerating distinct decision paths. Use dynamic programming when many paths reach the same state and only an aggregate answer is needed. Worst-case backtracking is usually exponential plus output-copy cost.

Explain It in an Interview

Say: “The path contains exactly the choices made so far. I apply one legal choice, recurse, and undo it so siblings start from identical state. This prune is safe because…” Then state branching factor, maximum depth, and output cost. Reusable-Candidate Combination Sum(opens in a new tab) exercises these decisions.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Binary event trace to length dO((d + 1) * 2^d)O((d + 1) * 2^d)The full tree has O(2^d) edges and each saved path copy costs up to O(d).
Unique width-k combinationsOutput- and search-tree-dependentO(n log n + n * 2^n)Sorting plus a conservative bound on branches and copies; pruning can reduce explored work.

Space

O(depth) active frames/path, plus output event or candidate storage.

Assumptions

  • A one-frame expansion drill is not the complexity of a full recursive search.
  • Copying nested objects is shallow; these Labs use scalar choices.

Invariants Worth Saying Aloud

  1. At entry, path contains exactly the choices on the current root-to-call path.
  2. After a child returns and the choice is undone, siblings see the same parent state.
  3. Saved outputs own copies rather than aliases of the mutable work path.

When To Use Or Avoid Backtracking

Use It When

  • Use backtracking for bounded enumeration or constraints that reject partial candidates.
  • Share one mutable path when every branch restores it and saved outputs are copied.

Choose Another Tool When

  • Use DP when many paths share a sufficient state and only an aggregate is required.
  • Do not prune merely because a current score looks worse; future choices may change it.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Saving an alias of the work path

Appending path itself records the same list. Later undo empties the saved candidate too.

Prevent it: Copy the path when saving output.

Avoid

result.append(path)

Use instead

result.append(path.copy())

Leaving the previous choice in a sibling

Without undo, choosing 1 after 0 produces [0,1] instead of independent siblings.

Prevent it: Restore the parent path after every child.

Avoid

for choice in (0,1):
    path.append(choice)
    result.append(path.copy())

Use instead

for choice in (0,1):
    path.append(choice)
    result.append(path.copy())
    path.pop()

Banning equal values at every depth

The second 2 can validly join the first 2 at a deeper level. Only equal alternatives at the same depth are duplicates.

Prevent it: Compare index with the current start, not global zero.

Avoid

skip = index > 0 and values[index] == values[index-1]

Use instead

skip = index > start and values[index] == values[index-1]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.