Sub topic 6
Trying Every Subset with Bitmasks
Many problems ask you to choose some items from a collection: a group of numbers that hits a target sum, a set of tasks that fits a time budget, a team that covers every required skill. The brute-force answer to all of them is the same. You try every possible selection and keep the ones that work. This chapter shows how to list every selection with simple integer loops, using the bits of a number to record which items are in and which are out.
This chapter assumes you can write loops and functions in Python, that you know what a list is, and that you can read Big-O notation such as O(n · 2^n). It also uses the cost-estimation habits from the earlier chapter on running time. You do not need any prior experience with bitwise operators. They are introduced here.
The subset search space
A subset of a collection is any selection of its items, including the empty selection and the full collection. Each item faces one independent yes-or-no decision: include it or leave it out. With n items there are n binary decisions, so there are 2 × 2 × … × 2 = 2^n subsets.
That count is the size of the search space. Every candidate solution is one subset. A brute-force solution must visit all 2^n of them, unless it can stop early after finding an answer. Each visit usually costs O(n) work to build or sum the subset.
The search space has a useful property here. A row of n yes-or-no decisions looks exactly like an n-bit binary number. Each integer from 0 to 2^n − 1 has a different bit pattern, and together these integers cover every pattern once.
Bits as include-or-exclude flags
Let the items be indexed 0 to n − 1. A mask is an integer whose bit i says whether item i is included: 1 means in, 0 means out. Three operators do all the work:
1 << nshifts 1 left by n places, giving 2^n.range(1 << n)therefore produces every mask from 0 to 2^n − 1.mask >> ishifts the mask right by i places, so bit i moves to the lowest position.& 1keeps only the lowest bit.(mask >> i) & 1is 1 when item i is in the subset and 0 when it is not.
Here are all eight masks for items ["a", "b", "c"]. Bit 0 is the rightmost digit and corresponds to "a".
| mask | binary | subset |
|---|---|---|
| 0 | 000 | [] |
| 1 | 001 | [a] |
| 2 | 010 | [b] |
| 3 | 011 | [a, b] |
| 4 | 100 | [c] |
| 5 | 101 | [a, c] |
| 6 | 110 | [b, c] |
| 7 | 111 | [a, b, c] |
Each subset appears exactly once, and nothing outside the search space appears. Those two facts are what make this enumeration correct.
Subset sum by brute force
The subset-sum problem asks whether any subset of items adds up to target. Translated directly into code, the enumeration looks like this:
def subset_sum_exists(items, target):
n = len(items)
for mask in range(1 << n):
total = sum(items[i] for i in range(n) if (mask >> i) & 1)
if total == target:
return True
return False
print(subset_sum_exists([3, 34, 4, 12, 5, 2], 9)) # True (4 + 5)
print(subset_sum_exists([3, 34, 4, 12, 5, 2], 30)) # FalseA yes-or-no answer is often not enough. When you debug, or when the problem asks for the selection itself, return the subset that worked. This version also works on any predicate, so the same loop serves many problems:
def first_subset(items, is_valid):
n = len(items)
for mask in range(1 << n):
chosen = [items[i] for i in range(n) if (mask >> i) & 1]
if is_valid(chosen):
return chosen
return None
print(first_subset([3, 34, 4, 12, 5, 2], lambda s: sum(s) == 9)) # [4, 5]The function returns [4, 5] because masks are tried in increasing order. Mask 20 (binary 10100, indices 2 and 4) is the first mask whose items sum to 9. The subset [3, 4, 2] also works, but its mask is 37, so the loop reaches 20 first.
The same structure handles optimization problems. To find the best subset under a constraint, you visit every mask, skip the ones that break the constraint, and keep the best score seen so far:
def best_knapsack(weights, values, capacity):
n = len(weights)
best_value, best_mask = 0, 0
for mask in range(1 << n):
w = sum(weights[i] for i in range(n) if (mask >> i) & 1)
if w > capacity:
continue
v = sum(values[i] for i in range(n) if (mask >> i) & 1)
if v > best_value:
best_value, best_mask = v, mask
chosen = [i for i in range(n) if (best_mask >> i) & 1]
return best_value, chosen
print(best_knapsack([2, 3, 4, 5], [3, 4, 5, 6], 5)) # (7, [0, 1])An optimization search cannot stop at the first valid subset, so it always pays the full 2^n cost.
Edge cases the bitmask handles for free
Bitmask enumeration covers several awkward inputs correctly without any extra code. You should still know what each one does.
- The empty subset. Mask 0 selects nothing, and its sum is 0.
subset_sum_exists([1, 2], 0)returnsTrue. If your problem requires a non-empty subset, start the loop at mask 1. - Empty input. When
n = 0,range(1 << 0)isrange(1), so the loop visits only mask 0.subset_sum_exists([], 0)isTrueandsubset_sum_exists([], 5)isFalse. Both answers are correct. - Duplicates. Masks select positions, not values. In
[2, 2, 3], the subsets{index 0, index 2}and{index 1, index 2}both sum to 5 and count as two different subsets. If the problem asks for distinct value-sets, you must remove the duplicates yourself, for example by collectingtuple(sorted(chosen))into a set. - Negative numbers. The enumeration makes no assumptions about values, so negatives are fine. That matters later. The backtracking version in the chapter on pruning relies on non-negative items to cut branches, and the plain bitmask loop makes a good reference to check it against.
What it costs
The outer loop runs 2^n times. The inner decoding costs O(n), so the whole search is O(n · 2^n). In CPython, plan for roughly 10^7 simple operations per second:
| n | 2^n | n · 2^n | rough CPython time |
|---|---|---|---|
| 10 | 1,024 | ~10^4 | instant |
| 15 | 32,768 | ~5 × 10^5 | well under 1 s |
| 20 | ~10^6 | ~2 × 10^7 | a few seconds |
| 25 | ~3.4 × 10^7 | ~8 × 10^8 | minutes |
| 30 | ~10^9 | ~3 × 10^10 | hours |
The working rule: when a problem's limit says n ≤ 20, the authors are usually inviting an exponential subset search. At n ≤ 40 they usually expect meet-in-the-middle, which enumerates each half separately at about 2^20 masks per half. At n in the hundreds or thousands, you need a polynomial method such as dynamic programming over sums.
Removing the inner O(n)
You can drop the factor of n when you need a value for every subset. Look at the lowest set bit of a mask. Clear that bit and you get a smaller mask whose total you have already computed. Add the one missing item and you have the total for this mask:
def all_subset_sums(items):
n = len(items)
sums = [0] * (1 << n)
for mask in range(1, 1 << n):
low = mask & -mask # isolates the lowest set bit
i = low.bit_length() - 1 # index of that bit
sums[mask] = sums[mask ^ low] + items[i]
return sums
print(all_subset_sums([1, 2, 4])) # [0, 1, 2, 3, 4, 5, 6, 7]This runs in O(2^n) time and uses O(2^n) memory. It is a small example of a theme in later chapters: the plain version recomputes each subset's sum from scratch, and reusing work you have already done removes that waste.
Alternatives to raw bitmasks
Python offers other ways to enumerate subsets. Each fits a different situation.
| technique | when it fits | trade-off |
|---|---|---|
| `range(1 << n)` with bit tests | need masks as keys, for DP or memo tables | slightly cryptic to read |
| `itertools.product([0, 1], repeat=n)` | readability matters most | builds a tuple per subset; slower |
| `itertools.combinations(items, k)` for each k | problem cares about subset size, such as "exactly k items" | you must loop over k yourself |
| recursion (include or skip) | you plan to prune branches | recursion overhead; covered in the pruning chapter |
Masks have one advantage the others lack. A mask is a single integer, so it can index a list or serve as a dictionary key. That makes the bitmask form the natural starting point for subset dynamic programming.
Exercises
Exercise
Write count_subsets(items, target) that returns how many subsets (by position) sum to target. What does it return for items = [2, 2, 3], target = 5?
Show answer
Loop for mask in range(1 << n), compute the sum of items[i] for set bits, and add 1 to a counter when it equals the target; never return early. For [2, 2, 3] and 5 it returns 2, because indices {0, 2} and {1, 2} are different positions even though their values match.
Exercise
Which mask represents the subset containing items at indices 1 and 3 out of n = 4, and how would you test whether index 2 is in a given mask?
Show answer
The mask is (1 << 1) | (1 << 3) = 2 + 8 = 10, binary 1010. Index 2 is in the mask exactly when (mask >> 2) & 1 == 1; for mask 10 that is 0, so index 2 is not included.
Exercise
A problem gives up to n = 30 items and asks whether any subset sums to a target. Is subset_sum_exists acceptable in Python, and if not, what should you consider?
Show answer
No. It needs about 30 × 2^30 ≈ 3 × 10^10 operations, which takes hours in CPython. Consider meet-in-the-middle (enumerate 2^15 sums for each half, then match them with sorting or hashing), or dynamic programming over sums if the values are small integers.
Exercise
Why does subset_sum_exists([5, -5], 0) return True on the very first mask, and how would you change the function if the problem requires a non-empty subset?
Show answer
Mask 0 is the empty subset, whose sum is 0, so it matches immediately. To require a non-empty subset, iterate range(1, 1 << n); the function then returns True via mask 3 (5 + -5 = 0).