Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Backtracking proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)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 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.
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.
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 eventsImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 eventsPredict 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. |
| 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.
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.
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 resultImplement unique_combinations(values, width). Return lexicographically ordered unique combinations of the requested width; each input index is used at most once.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 resultUse 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.
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 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Backtracking proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Binary event trace to length d | O((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 combinations | Output- and search-tree-dependent | O(n log n + n * 2^n) | Sorting plus a conservative bound on branches and copies; pruning can reduce explored work. |
O(depth) active frames/path, plus output event or candidate storage.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Appending path itself records the same list. Later undo empties the saved candidate too.
Prevent it: Copy the path when saving output.
result.append(path)result.append(path.copy())Where you will hit this: Extend a Path by One Choice(opens in a new tab)
Without undo, choosing 1 after 0 produces [0,1] instead of independent siblings.
Prevent it: Restore the parent path after every child.
for choice in (0,1):
path.append(choice)
result.append(path.copy())for choice in (0,1):
path.append(choice)
result.append(path.copy())
path.pop()Where you will hit this: Extend a Path by One Choice(opens in a new tab)
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.
skip = index > 0 and values[index] == values[index-1]skip = index > start and values[index] == values[index-1]Where you will hit this: Reusable-Candidate Combination Sum(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
python-docs · checked 2026-07-27