Skip to the workspace
Pebellslearn by building
Greedy, Backtracking & Dynamic Programming  ›  Lesson

Backtracking & Exact-Length Mixes

Backtracking 40 minExplore choices one at a time, and back out of dead ends

dsa / Backtracking & Exact-Length Mixes

Explore each scene at your own pace.

01 · Finding every two-track mix

Finding every two-track mix

Backtracking & Exact-Length Mixes

Definition
Backtracking solves a problem by building an answer one choice at a time, recursing on what follows, undoing the choice, and abandoning any partial answer that cannot lead to a valid result.
In plain words
Think of working through a maze by trying a turn, and if it leads nowhere, stepping back to the last junction and trying the next turn. You keep one trail of choices that grows as you go forward and shrinks as you back up.

In short: backtracking tries choices systematically and abandons a branch the moment it can't work. Every call does the same three things: choose (add one option to the path), explore (recurse on everything that follows), un-choose (undo the choice before trying the next one). The path is one shared list that grows and shrinks as the search goes deeper and comes back — never a formula, just disciplined trial and error. Subsets cost O(n · 2ⁿ), permutations O(n · n!), and a continue that skips a branch that can't work (pruning) cuts real work without changing that worst case.

Four snapshots of the path list: choose A, choose B, un-choose B back to [A], then choose C — one shared list growing and shrinking

Finding every two-track mix

Tunebox Radio has a 7-minute gap before the news, and the DJ wants every combination of tracks that fills it exactly, not just one. Start with the simplest shape — every subset of a list — choosing, recursing, then undoing:

python

path is one list shared by every call. start only offers tracks after the last one chosen, so ["Blink", "Aurora"] never shows up as a second copy of ["Aurora", "Blink"].

step through it
1out, path = [], []
2def explore(start):
3 out.append(path[:])
4 for i in range(start, 2):
5 path.append("AB"[i])
6 explore(i + 1)
7 path.pop()
8explore(0)
9print(out)

❓ Cross-question: "Why path[:] and not just path?" path keeps changing. Appending path itself stores a reference, so every entry in out ends up the same list — empty by the time the search finishes. path[:] stores a snapshot.

The mistake: recording the live list instead of a copy. Every "subset" ends up pointing at the same emptied-out path:

broken — fix it

This should print all four subsets of ["a", "b"]. It prints four empty lists. Make each recorded subset keep its contents.

Draw each call as a node and each loop step as an edge to a child — three tracks make exactly 2³ = 8 calls, one per subset:

watch it move · graph

Each call is one node and records one subset, so three tracks make 2³ = 8 calls.

explore(0) records the empty subset, then loops over A, B and C. 8 nodes, 7 edges, directed. At []. Settled: [].

1 / 8
What does this print?
def count_nodes(n, start=0):
    return 1 + sum(count_nodes(n, i + 1) for i in range(start, n))

print(count_nodes(5))
Scene 1 of 7
Project context and further resources
You're building a piece ofTunebox — festival planner
This piece — exact_mixes(): Every combination of tracks that fills a slot exactly.
Scenario Tunebox Radio has a fixed gap before the news and can't run dead air. The mix finder lists every combination of tracks that fills it to the minute, so the DJ can pick one.
exact_mixes.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
exact_mixes(tracks, slot) → listEvery combination of track names that fills the slot exactly.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.