Skip to contentKEEP THE CRAFTTHE SANCTUARY

Choose / Explore / Unchoose

Keep a partial candidate in shared mutable state, explore one choice, then restore every change before a sibling starts. Copy completed answers so later undo cannot alter them.

1 practice exercise14 interview problems

Recognize it when The task enumerates paths, permutations or assignments through a decision tree.

Checking your account…

Choose / Explore / Unchoose Code Labs

Give Each Frame Responsibility for One Choice

A backtracking path is the sequence of choices on the current recursion stack. One frame appends a choice and owns the matching removal. A sibling must see the exact prefix that existed before that choice; otherwise it explores a different subproblem and may reuse unavailable elements.

Inspect the Lifecycle before Recursing

The first Lab isolates one decision depth. Its choose event snapshots the path after append. Its undo event snapshots that same path immediately before pop; the label identifies the action about to happen, not an already-restored path. This makes the change and its reversal visible without introducing a second recursive algorithm.

Trace Choice Lifecycles

Reference
def choice_lifecycle(choices):
    path=[]; events=[]
    for choice in choices:
        path.append(choice); events.append(["choose",path.copy()]); events.append(["undo",path.copy()]); path.pop()
    return events
Practice

Implement choice_lifecycle(choices). Return [choose,path] after appending each choice and [undo,path] immediately before removing it, for one decision depth. Each path is a separate snapshot.

Public tests

  • Undo each applied choice

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

Trace Choice Lifecycles

def choice_lifecycle(choices):
    path=[]; events=[]
    for choice in choices:
        path.append(choice); events.append(["choose",path.copy()]); events.append(["undo",path.copy()]); path.pop()
    return events

See Undo Capture the Pre-Pop Path

Predict choice_lifecycle([3,8]). Each undo event is recorded before the actual removal, and both siblings begin with an empty path.

Step Executed statement State Why
1 path.append(choice); events.append(["choose",path.copy()]) choice=3; path=[3]; events=[["choose",[3]]] The chosen value appears in its own snapshot.
2 events.append(["undo",path.copy()]); path.pop() events end with ["undo",[3]]; path=[] The event describes the impending removal; pop restores the parent.
3 path.append(choice); events.append(["choose",path.copy()]) choice=8; path=[8] Restoration prevents 3 from leaking into this sibling.
4 events.append(["undo",path.copy()]); path.pop() path=[]; events contain four independent snapshots The second branch leaves the same empty parent state.
Print Output
print(choice_lifecycle([3,8])) [['choose', [3]], ['undo', [3]], ['choose', [8]], ['undo', [8]]]

Restore Both the Path and Availability

The permutation Lab adds used flags indexed by input position. A legal choice marks its position, appends the value and recurses. On return, pop removes the value and resetting used permits that position in the next sibling. Restoring only one structure breaks their agreement.

Generate Permutations

Reference
def permutations(values):
    result=[]; path=[]; used=[False]*len(values)
    def search():
        if len(path)==len(values): result.append(path.copy()); return
        for index,value in enumerate(values):
            if used[index]: continue
            used[index]=True; path.append(value); search(); path.pop(); used[index]=False
    search(); return result
Practice

Implement permutations(values). Return all position-based permutations in choice order without mutating values. Equal values at different positions are distinct choices and may produce duplicate value sequences.

Public tests

  • Restore path and availability

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

Generate Permutations

def permutations(values):
    result=[]; path=[]; used=[False]*len(values)
    def search():
        if len(path)==len(values): result.append(path.copy()); return
        for index,value in enumerate(values):
            if used[index]: continue
            used[index]=True; path.append(value); search(); path.pop(); used[index]=False
    search(); return result

At a complete path, save path.copy(). Saving path itself would store repeated references to one list that later becomes empty. This Lab treats equal-valued positions as separate choices, so repeated values can produce duplicate value sequences. Unique-value permutation questions require a separate duplicate policy; this implementation does not promise that policy. Empty input has one permutation, the empty path.

Estimate the Search in an Interview

For n distinct values, there are n! complete answers and copying each length-n path costs O(n*n!) time and output space. The active path, flags and recursion use O(n) working space. Pruning reduces explored branches only when a partial constraint proves that no completion is valid. Memoization is a better boundary when only a count or optimum is needed and the complete remaining state repeats; caching a partial path indiscriminately does not preserve enumeration semantics.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Backtracking: choose, explore, un-choose

Choose, explore, un-choose.

You must list every combination, subset, permutation or arrangement that satisfies a rule.

Trigger words

  • all combinations
  • all subsets
  • all permutations
  • generate all
  • n-queens
  • generate parentheses
  • palindrome partitioning
  • word search
def subsets(nums):
    result = []
    path = []

    def backtrack(start):
        result.append(path[:])          # record a copy of the current choice
        for i in range(start, len(nums)):
            path.append(nums[i])        # 1. choose
            backtrack(i + 1)            # 2. explore
            path.pop()                  # 3. un-choose

    backtrack(0)
    return result

Spot it when

  • 'All subsets / combinations / permutations'.
  • 'All ways to place / split / generate'.
  • Small input (n up to about 20).

Remember

  • Append a copy (path[:]), never path itself.
  • start prevents picking earlier items again, so each set appears once.
  • Knob rhyme: i + 1 for no reuse, i for reuse; sort and skip same-level twins.

How problems bend it

  • Combinations of size k: Record only when len(path) == k, then return.
  • Permutations: Loop over all items and skip the ones already used (keep a used set).
  • Reuse allowed (combination sum): Recurse with backtrack(i) instead of backtrack(i + 1) and stop when the sum is too big.
  • Input has duplicates: Sort first and skip nums[i] when i > start and nums[i] == nums[i - 1].
  • Permutations with duplicates: Sort, keep a used list, and skip nums[i] when it equals nums[i - 1] and nums[i - 1] is not used.
  • Prune early: With sorted input, break out of the loop as soon as the running total passes the target.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Generate permutations of n input positionsO(n*n!)O(n*n!)With distinct values there are n! leaves and each answer copy has length n.

Space

O(n) working path, flags and recursion; O(n*n!) returned output.

Assumptions

  • The loop scans n positions at each internal frame; the complete search plus copying is O(n*n!) in the unit-cost element model.
  • The one-depth lifecycle trace uses O(c) time and output for c supplied choices; it is not a full recursion tree.
  • list.copy() is shallow; it is sufficient for integer values but does not clone nested mutable choices.

Invariants Worth Saying Aloud

  1. path contains exactly the values chosen by the active recursive frames.
  2. used identifies positions currently represented in path.
  3. After a child returns, path and used equal their pre-choice parent state.
  4. Each recorded complete answer owns a separate list snapshot.

When To Use Or Avoid Choose / Explore / Unchoose

Use It When

  • A manageable search tree permits enumeration and local choices have reversible state changes.
  • Constraints can reject partial candidates before constructing full answers.

Choose Another Tool When

  • Only a count or optimum is needed and repeated complete future states admit DP.
  • Input size makes exhaustive output infeasible; prune with a proved constraint or choose a different formulation.

Common Pitfalls

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

Saving the shared path as an answer

A later pop changes the same list already stored in result.

Prevent it: Copy the completed path when recording an answer.

Avoid

result.append(path)
path.pop()

Use instead

result.append(path.copy())
path.pop()

Leaving a choice in the next sibling

Without the matching pop, the second branch inherits the first branch's choice.

Prevent it: Undo the append after each explored child.

Avoid

for choice in [3,8]:
    path.append(choice)

Use instead

for choice in [3,8]:
    path.append(choice)
    path.pop()

Popping the path but forgetting the used flag

The parent path is restored but the position remains unavailable, excluding a legal sibling.

Prevent it: Reverse both mutations owned by the completed choice.

Avoid

path.pop()

Use instead

path.pop()
used[index]=False

Reviewed References

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