Sub topic 6
Trying Every Subset with Bitmasks
This chapter assumes you can write loops and functions in Python, know what binary numbers are, and can read Big-O notation. It builds on the search-space idea from earlier chapters. Here the candidates are no longer pairs. Each candidate is a choice of which items to include.
The search space of "pick some items"
Many problems ask whether some group of items meets a condition. Can some coins add up to exactly 17? Which set of tasks fits in a time budget? Is there a team with every needed skill? In each case a candidate solution is a subset: every item is either in or out.
With n items there are two choices per item, so there are 2^n subsets. A brute-force solution checks all of them. To do that, you need a way to list every subset exactly once, with none skipped and none repeated.
One integer per subset
Count from 0 to 2^n - 1 and read each number in binary. Bit i of the number says whether item i is included. Every integer in that range gives a different subset, and every subset matches exactly one integer. That integer is called a mask.
For items = [3, 5, 7]:
| mask | binary (bit 2, 1, 0) | subset | sum |
|---|---|---|---|
| 0 | 000 | {} | 0 |
| 1 | 001 | {3} | 3 |
| 2 | 010 | {5} | 5 |
| 3 | 011 | {3, 5} | 8 |
| 4 | 100 | {7} | 7 |
| 5 | 101 | {3, 7} | 10 |
| 6 | 110 | {5, 7} | 12 |
| 7 | 111 | {3, 5, 7} | 15 |
The code
The expression (mask >> i) & 1 shifts bit i down to position 0 and keeps only that bit. The result is 1 if item i is in the subset and 0 if it is not.
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
def subset_sum_witness(items, target):
"""Return one subset that hits the target, or None."""
n = len(items)
for mask in range(1 << n):
chosen = [items[i] for i in range(n) if (mask >> i) & 1]
if sum(chosen) == target:
return chosen
return None
print(subset_sum_exists([3, 5, 7], 10)) # True
print(subset_sum_witness([3, 5, 7], 10)) # [3, 7]
print(subset_sum_exists([3, 5, 7], 11)) # FalseReturning the subset that matched (the witness) instead of just True makes the code much easier to debug. You can check the answer by hand.
Cost
The outer loop runs 2^n times. Decoding each mask takes n steps, so the total is O(n · 2^n). Plugging in input limits, as in the estimation chapter:
| n | 2^n · n (approx.) | Plain Python |
|---|---|---|
| 15 | 5 × 10^5 | instant |
| 20 | 2 × 10^7 | a few seconds |
| 25 | 8 × 10^8 | too slow |
A limit of n ≤ 20 in a problem statement often hints that a solution enumerating every subset is the intended answer.
Common errors
- Dropping the last subset.
range((1 << n) - 1)stops at2^n - 2and never tries the subset with every item. - Testing the bit the wrong way.
mask & (1 << i) == 1is wrong fori > 0, because the masked value is2^i, not 1. Test!= 0, or use(mask >> i) & 1. - Forgetting the empty subset. Mask 0 means no items, with sum 0. If
target == 0, the function returnsTrue. Decide whether the problem allows an empty choice. If it does not, start the loop at 1. - Precedence surprises.
1 << n - 1means1 << (n - 1). Add parentheses when you are unsure.
Exercise
Write count_subsets(items, target) that returns how many non-empty subsets of items sum to target. What does it return for items = [1, 2, 3, 4] and target = 5?
Show answer
Loop mask over range(1, 1 << n) to skip the empty subset, compute each sum with (mask >> i) & 1, and add 1 to a counter on every match. For [1, 2, 3, 4] with target 5 the matching subsets are {1, 4} and {2, 3}, so it returns 2.
Exercise
A problem gives up to 40 items. Is enumerating every subset with bitmasks feasible? Explain using the cost formula.
Show answer
No. 2^40 is about 1.1 × 10^12 masks, and multiplying by n = 40 gives about 4 × 10^13 steps. That is far beyond what runs in seconds, so you would need pruning or a different algorithm.