On this page · Give Each Frame Responsibility for One Choice
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.
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.
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
Python 3.11+
list.copy() is shallow; it is sufficient for integer values but does not clone nested mutable choices.