Subsets
medium 22 minGenerating every subset is the first backtracking pattern most interviews ask for, and there are four standard ways to write it: take-or-skip recursion, a start-index loop, iterative cascading and bitmask counting.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Every element: in or out. Two choices, n times, 2ⁿ subsets.
Packing for a trip with a shirt, pants and a hat. For each item you decide take it or leave it, so there are 2 × 2 × 2 = 8 ways to pack, from the empty suitcase to taking everything. Or think of a row of light switches, one per element: every way of setting them is one subset, and read left to right the switches spell a binary number.
Cheat sheet
- Count
- 2ⁿ (empty and full included)
- Time
- O(n · 2ⁿ)
- Extra space
- O(n) path and stack
- Start index
- save, loop from start, recurse i + 1
- Take or skip
- 2ⁿ leaves, 2ⁿ⁺¹ - 1 calls
- Cascade
- result += [s + [x] for s in result]
- Bitmask
- range(1 << n), take i if mask >> i & 1
- Subsets II
- sort, skip if i > start and equal to i - 1
- Practical n
- up to about 20
Spot it when you see
- Find all possible combinations of items.
- Generate all subsets that satisfy a rule.
- Can the array be partitioned into groups with some property?
- Select items so that a condition holds.
- Choose or do not choose each element.
- All ways to pick from a set, with n around 20 or less.
Tricks that stick
- FAIS: Forward only, Add every path, Include the element, Subtract it after.
- Light switches: one per element, 2ⁿ settings, and the settings are binary numbers.
- Start index looks forward, so [2, 1] is never built.
- Duplicates: sort, then the second copy may follow the first but may not replace it.
- Every append has a pop.
Do not forget
- Saving path instead of a copy of path.
- Looping from 0 instead of start, which builds [1, 2] and [2, 1].
- Forgetting the pop after the recursive call.
- Dropping the empty subset (starting masks at 1).
- Subsets II with i > 0 instead of i > start, or without sorting first.
- Appending to the list you are iterating over in the cascading version.