Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 54 / 66

Choose. Explore. Undo..

Enumerate candidates while restoring state between branches.

BY NAVAN SAMI◷ 9 MIN READSTRETCHALGORITHM

01 Model the idea

Backtracking explores a decision tree. Make one choice, recurse on the remaining problem, then undo that choice before exploring a sibling branch. Pruning stops branches that already violate constraints. The technique is powerful but can still require exponential or factorial work; a search tree’s size does not vanish because the code is short.

THE THING THAT MUST STAY TRUE

The current path contains exactly the choices made on the active branch.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
CHOOSE one unused option
EXPLORE the smaller remaining problem
UNDO the choice
RECORD only complete candidates

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

backtracking.py
def permutations(values):
    result, path, used = [], [], set()
    def visit():
        if len(path) == len(values):
            result.append(tuple(path)); return
        for index, value in enumerate(values):
            if index not in used:
                used.add(index); path.append(value)
                visit()
                path.pop(); used.remove(index)
    visit()
    return result
print(permutations(["A", "B"]))
↳ EXPECTED OUTPUT
[('A', 'B'), ('B', 'A')]
  1. 1

    The path and used positions describe the current partial candidate. Each recursive return restores exactly the earlier state.

  2. 2

    Copying the finished path into a tuple matters. Appending the same mutable list reference would make stored results change during later backtracking.

  3. 3

    This version treats positions as distinct. Duplicate input values can produce duplicate value permutations; a multiset-aware search must avoid equivalent branches deliberately.

04 Count the cost

TIME

O(n·n!) including materialised permutations

SPACE

O(n) search state plus O(n·n!) stored output

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Generate all length-two binary strings with recursive choice and undo.

Reveal one possible solution +
one_possible_solution.py
result, path = [], []
def visit():
    if len(path) == 2:
        result.append("".join(path)); return
    for bit in "01":
        path.append(bit); visit(); path.pop()
visit()
print(result)

06 Check your reasoning

QUICK SIGNAL CHECK

Why undo a choice after returning from recursion?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.