Lesson 1 of 2
The choice tree
Every subset is a path of keep-or-drop choices, and every ordering a path of "which unused item next". Walk that tree depth first with one shared list, choosing, exploring and unchoosing at every box, and you can list every answer exactly once.
Draw the choice tree for the subsets or orderings of a short list, and count its leaves and its calls
Write a backtracking search that chooses, explores and unchooses at every call
Explain why each answer is saved as a copy of the path
Track which items are already placed with a list of booleans
State what listing every subset or ordering costs, and why nothing can do better
Your sales report needs a subtotal for every combination of three columns: region, channel and device. In many SQL engines that is one clause, GROUP BY CUBE(region, channel, device), and the database produces all 8 groupings, from all three columns down to none (the grand total).
In an interview there is no CUBE. You get "return every subset of this list" and a blank editor. Eight combinations you could list by hand. Ten items have 1,024, and for a list whose length you do not know in advance, you cannot write the right number of nested loops. You need a method that makes one decision at a time and never misses or repeats an answer.
That method is called backtracking: try a choice, explore everything that follows from it, undo it, try the next choice. This lesson builds it from one picture, the choice tree, and uses it for subsets, orderings and the letters on a phone keypad.
Every subset is a path of choices
How do you list every subset without missing one or listing one twice? Take the list ["a", "b", "c"]. In the figures, and when a sentence names an item, we drop the quotes: a, b and c. A subset keeps some of the items and drops the rest. Decide one item at a time, in order: keep it or drop it. The decision about a gives two possibilities. Each of them then decides b and splits in two again, and then each decides c. Three decisions with two outcomes each give 2 × 2 × 2 = 8 ways, and each way is one subset. Keep all three and you get [a, b, c]; drop all three and you get [].
Draw the decisions as a tree. The top box, the root, has decided nothing. Each box below has decided one more item than the box above it. A box at the bottom, called a leaf, has decided every item, so it holds one finished subset. Each subset is the path of choices from the root down to its leaf. That picture is the choice tree.
The figure grows that tree one call at a time. Each box is one call of a recursive function (a function that calls itself, from module 8), subsets(i, path): i is the position of the next item to decide, and path lists the items kept so far. Each box shows its path, and each line down is labelled with its choice. The figure says take and skip where we say keep and drop.
As in module 8, every call is two steps, one when it is made and one when it returns. The readouts count the calls made, the depth (the calls that have started and not yet returned, waiting on the call stack) and the subsets saved. Before you press Next, guess which subset is saved first and which last.
Each item doubles the leaves. One item gives 2 subsets, two give 4, three give 8, and n items give 2n. The boxes above the leaves are calls too: for three items the four levels hold 1, 2, 4 and 8 calls, which adds up to the 15 the figure reported.
The subsets tree for 3 items made 15 calls: 1 + 2 + 4 + 8, level by level from the root down to the 8 leaves. How many calls does the subsets tree for 5 items make in all, leaves included? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Choose, explore, unchoose
How does code walk that tree? It goes depth first: all the way down one branch to a leaf, then back up to the nearest box with a branch not yet tried, then down that branch. One list, path, holds the items kept on the branch we are on. Going down a keep branch appends an item; coming back up removes it.
Here is the smallest version: two items, and each leaf prints its subset instead of saving it. Before you step through, guess the four lines it prints, in order.
items = ["a", "b"]path = []def explore(i):if i == len(items):print(path)returnpath.append(items[i])explore(i + 1)path.pop()explore(i + 1)explore(0)
(nothing printed yet)The three moves are choose, explore and unchoose. Choose: path.append(items[i]) keeps the item. Explore: explore(i + 1) lists every subset below that choice. Unchoose: path.pop() removes the item again, and then the drop branch explores with it left out.
Why undo? Because both branches share one path. The drop branch of a box must start from exactly the path its keep branch started from. So every call keeps a promise: when explore(i) starts, path holds the kept items among items[0] to items[i - 1], and when it returns, path is back the way the call found it.
Here are the two branches swapped, on three numbers. Predict the new output.
This version explores the drop branch first and the keep branch second. Type exactly what it prints, one line per subset.
items = [4, 7, 9]
path = []
def explore(i):
if i == len(items):
print(path)
return
explore(i + 1) # drop items[i]
path.append(items[i]) # keep items[i]
explore(i + 1)
path.pop()
explore(0)
And what if the unchoose step goes missing?
The unchoose step is gone from this version:
items = ["a", "b"]
path = []
def explore(i):
if i == len(items):
print(path)
return
path.append(items[i])
explore(i + 1)
explore(i + 1)
explore(0)
What does it print?
Choose one answer, then check.
So far: a subset is a path of keep-or-drop choices, n items have 2n of them, and the code walks the tree depth first with one shared path, choosing, exploring and unchoosing at every box.
Saving each answer
Printing is not the job: a real problem asks you to return the subsets as a list of lists. The first change that comes to mind is to append path to a result list at each leaf. Predict what that does.
Each leaf now appends path to result. Type exactly what this prints.
items = [4, 7]
path = []
result = []
def explore(i):
if i == len(items):
result.append(path)
return
path.append(items[i])
explore(i + 1)
path.pop()
explore(i + 1)
explore(0)
print(len(result))
print(result)
result.append(path) stores the list itself, not what is in it. Module 1 called this aliasing: one list reached through two names. Here path and all four items of result are that one list, which keeps changing and ends empty, so result shows the empty list four times. Save a snapshot instead: path[:] makes a new list holding what path holds right now. list(path) does the same. Here is the search from that exercise with path[:] at the leaf. It prints result, then path. Run it.
It prints [[4, 7], [4], [7], []] and then []. Each copy kept what path held at its leaf, while path itself went back to empty. Change path[:] back to path and run it again: the four empty lists come back.
Now write it yourself. Put path, result and explore inside the function, so every call of subsets starts fresh. As in module 8, a function defined inside another can read the outer function's names and change the lists they point at. Before you type, decide what an empty list should return.
An empty list has one subset, the empty one, so the answer is [[]], not []: explore(0) is a leaf at once and saves a copy of the empty path.
Undo is needed only because path is shared. When each call gets its own copy of the notebook, there is nothing to put back. A number passed as an argument works that way: explore(i + 1, total + nums[i]) hands the next call a new total and leaves this call's total alone. Use that on a new question.
Write subset_sums(nums), which returns the sum of every subset of nums, one sum per subset, in any order. [1, 2, 3] has 8 subsets, so the answer has 8 sums: 6, 3, 4, 1, 5, 2, 3 and 0. The sum of [1, 2] and the sum of [3] are both 3, and both count.
This time the notebook is a number passed as an argument, explore(i, total), so there is no path and nothing to undo. When your tests pass, press Watch it run and look at the total in each box.
raise NotImplementedError, then press Run tests. Each check says what it expects.Orderings: which unused item next
What changes when order matters? A permutation is one way to line up all the items in a row, using each exactly once, so [a, b] and [b, a] are two different answers. The choice at each level changes: not keep or drop, but which unused item goes in the next spot. For [a, b, c], the first spot can take any of the 3 items, the second any of the 2 left, the last only the 1 remaining: 3 × 2 × 1 = 6 leaves. For n items that is n × (n - 1) × ... × 1, written n! and read "n factorial".
The figure draws that tree. Its function is permute(path, rest): path holds the items placed so far and rest the items not placed yet, so permute([a], [b, c]) has placed a and can put b or c next. Each box shows its path. Each call hands its child a new, shorter rest, so rest never needs an undo; path is shared, so it does. Before you press Next, guess which ordering is saved second.
The tree has more branches near the top and fewer below: 1 call at the root, 3 under it, then 6, then 6 leaves, which is the 16 calls the figure counted.
The trace below, like the problem's solution, tracks the free items in a second shared notebook instead of a new rest per call. To know which items are free, keep a list of booleans (True or False values), used, one per position. used[i] is True while items[i] sits in path, so checking an item is one lookup, where items[i] in path would scan the path.
Each box loops over every position and skips the used ones with continue (from module 1: skip the rest of this pass and go on to the next i). For each free one it runs choose (mark it, append it), explore, and unchoose (pop it, unmark it). Watch it on two items. Before you step, guess how many times the loop meets a used item and skips it.
items = ["a", "b"]path = []used = [False] * len(items)def explore():if len(path) == len(items):print(path)returnfor i in range(len(items)):if used[i]:continueused[i] = Truepath.append(items[i])explore()path.pop()used[i] = Falseexplore()
(nothing printed yet)Count a bigger tree by hand before the problem.
On paper, count the calls in the orderings tree for 4 items, [1, 2, 3, 4], level by level. The root places nothing; each level below it fills one more spot. Reveal one step at a time.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now the full problem. Its largest test has eight numbers, 40,320 orderings and a one-second limit. Never place a used number. Filling every spot with any of the 8 numbers and throwing out the lists with repeats would build 88 = 16,777,216 lists to keep 40,320.
Both undo steps matter. Leave out used[i] = False and that number stays blocked for the rest of the search, so orderings go missing: on [a, b, c] the search saves [a, b, c] and nothing else.
More than two branches
What does the template look like when a box has more choices? Subsets had two branches at every box. Orderings had a number of branches that shrank by one per level. In general, each box loops over the choices open at its level and runs choose, explore, unchoose for each one. When every level offers the same choices, that loop is a plain for over them.
Here is that shape at its smallest: every sequence of n coin flips, each "H" or "T". Two branches per box, like subsets, but both branches add a letter. This version passes path and result as arguments instead of nesting a function.
Put the lines in order to build flips(n, path, result), which appends to result every string of n coin flips, each "H" or "T", with "H" tried first. Called as flips(2, [], out), it fills out with "HH", "HT", "TH", "TT". Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
if len(path) == n:returnpath.pop()def flips(n, path, result):flips(n - 1, path, result)result.append(path)result.append("".join(path))for side in "HT":path.append(side)flips(n, path, result)
Letters from phone digits is the same tree with three or four branches per box. Each digit is one level, and its choices are the letters on its key: key 5 carries j, k and l, and key 6 carries m, n and o. So the digits "56" give 3 × 3 = 9 strings, from "jm" to "lo".
One trap before you start: think about what an empty string of digits should return.
With no digits the search would save one empty string, giving [""], so return [] before the search starts.
What it costs
How big can n get before listing everything is too slow? Every problem in this lesson asks for all the answers, so the size of the answer sets the cost. Here is how fast the two counts grow:
| n | Subsets, 2n | Orderings, n! |
|---|---|---|
| 3 | 8 | 6 |
| 5 | 32 | 120 |
| 8 | 256 | 40,320 |
| 10 | 1,024 | 3,628,800 |
| 20 | 1,048,576 | about 2.4 × 1018 |
Each leaf copies a path of up to n items, so listing every subset costs O(n · 2n) time and every ordering O(n · n!). No method can do better, because writing the answer out takes that long. The extra space is small: path holds at most n items, and the call stack is at most n + 1 calls deep (4 for three items, as both figures showed), far below the 1,000 nested calls plain Python allows by default.
Small limits in a problem are a signal. Module 2's rule of thumb is about 107 simple steps per second, so n up to about 20 allows 2n work, and n up to about 10 allows n!. The problems here say at most 10 numbers for subsets and 8 for orderings. When the limit is 105, a choice tree is the wrong tool.
A function returns every subset of a list of n different numbers, each subset saved as its own list. What is its time cost?
Choose one answer, then check.
Last, say the plan for orderings the way you would before typing.
Explain, as you would to an interviewer before typing, how you would return every ordering of a list of different numbers. Cover the walk, the notebook, the promise and the cost, and say why each answer is saved as a copy.
Saved in this browser as you type.