Subsets as Bitmasks
Enumerating subsets and submasks, the 3ⁿ bound and sums over subsets.
Looping over every subset of every subset of 15 items sounds like steps. It is , and a one-line loop, s = (s - 1) & m, visits exactly the right pairs. Summing a function over all subsets of every set needs even less, additions, and the same transforms power the fastest known exact algorithms for graph coloring.
What you’ll learn
- Enumerate the submasks of a mask with , and prove that it visits each exactly once, in decreasing order.
- Prove that enumerating all submasks of all masks costs , and use it for dynamic programming over set partitions.
- Generate all -subsets in increasing order with Gosper's hack, and derive why it works.
- Compute sums over subsets in , OR-convolutions, and the subset convolution in , and connect them to algorithms for NP-hard problems.
Walking the submasks of a mask
A submask of is a mask with : the subset . If has set bits it has submasks, and testing all masks to find them wastes time when is small. The standard loop jumps straight from one submask to the next:
def submasks(m):
s = m
while True:
yield s # m first, then smaller submasks, 0 last
if s == 0:
break
s = (s - 1) & m
print([format(s, '05b') for s in submasks(0b10110)])
# ['10110', '10100', '10010', '10000', '00110', '00100', '00010', '00000']The empty set must be handled on purpose: the test s == 0 sits after the yield, so 0 is visited once and the loop stops. Supersets of within bits are walked upward the same way: s = (s + 1) | m while s < 1 << n.
Let the set bits of be at positions . Reading a submask's bits at those positions gives a -bit number, and this compression is an order-preserving bijection from the submasks of onto :
Let have its lowest set bit at . Subtracting 1 clears that bit and sets every lower bit; masking with keeps, among the lower bits, exactly :
In compressed coordinates that is the borrow of an ordinary decrement: bit becomes 0 and bits become 1. So the loop counts down from to , visiting every submask exactly once.
How many masks does the loop visit for , counting itself and ?
Show the answer
8
has three set bits, so it has submasks: the compressed counter runs . The other five-bit masks are never touched.
The 3ⁿ bound, and DP over partitions
| masks | pairs | pairs of masks | |
|---|---|---|---|
| 10 | 1,024 | 59,049 | |
| 15 | 32,768 | ||
| 18 | 262,144 | ||
| 20 |
The classic use is dynamic programming over set partitions: split items into groups, where a group costs , minimizing the total. For each mask , choose the group that contains 's lowest item; that canonical choice counts each partition once instead of once per ordering of its groups.
def min_partition_cost(n, cost): # cost[s]: the cost of one group s (s != 0)
best = [0] + [float('inf')] * ((1 << n) - 1)
for m in range(1, 1 << n):
low = m & -m # the group must contain m's lowest item
s = m
while s: # every non-empty submask of m
if s & low:
best[m] = min(best[m], best[m ^ s] + cost[s])
s = (s - 1) & m
return best[(1 << n) - 1]time and memory, against the Bell number of partitions for brute force (). Typical uses: grouping people into teams, covering items with bundles, and the natural DP for graph coloring.
A solution loops for m in range(1 << n): for s in range(1 << n): if s & m == s: .... How does its running time compare with the submask loop?
- Same: both visit each pair once
- It costs instead of : it tests every pair of masks, most of which fail
- It costs
- It costs
Show the answer
B. It costs instead of : it tests every pair of masks, most of which fail
The inner loop runs times for every , so tests in all, of which only succeed. For : about tests instead of useful steps.
Gosper's hack: every k-subset in order
To visit only the subsets of size exactly , there are of them, you need the next larger integer with the same number of 1 bits. Bill Gosper's trick, item 175 of MIT's HAKMEM memo (1972), computes it with a handful of word operations:
def k_subsets(n, k):
"""All n-bit masks with exactly k ones, in increasing order (1 <= k <= n)."""
x = (1 << k) - 1 # the smallest: the k lowest bits
while x < 1 << n:
yield x
c = x & -x # lowest set bit
r = x + c # the carry ripples through the lowest block of ones
x = (((r ^ x) >> 2) // c) | r # refill the block's leftover ones at the bottom
print([format(x, '05b') for x in k_subsets(5, 3)][:4]) # ['00111', '01011', '01101', '01110']In C++, use unsigned (so -x is well defined) and / for the division: unsigned c = x & -x, r = x + c; x = (((r ^ x) >> 2) / c) | r;.
Write with its lowest block of ones followed by zeros, under a prefix . The next larger number with the same popcount moves the block's top 1 up one place and drops the other ones to the very bottom:
The lowest set bit is , and adding it carries through the whole block:
The XOR marks the bits that changed, ones above zeros. Shifting right by 2 and dividing by leaves , exactly ones at the bottom:
OR-ing them into gives . For example : , , ; shifted right by 2 that is , and divided by is , so .
Sums over subsets and subset convolution
The sum over subsets (zeta transform) could be computed with the submask loop in steps. Treating the hypercube one dimension at a time, as in 2-D Prefix Sums & Inclusion–Exclusion, does it in additions. Here is why the bit-by-bit loop is correct:
Process bits in turn; for bit , every mask containing does . Claim: after bits are processed, sums over the subsets of that agree with on all bits :
Initially () only qualifies. Processing bit : if nothing changes and nothing should. If , the qualifying for either contain , counted in , or do not, counted in :
After all bits the agreement condition is empty, so . Running the loops with subtraction inverts each step, which is Möbius inversion.
Transforms turn products of set functions into pointwise products. For the OR-convolution , a pair is counted in exactly when both and are subsets of , so , and in .
The subset convolution wants disjoint pairs: . Disjointness is invisible to , but sizes reveal it: and hold together exactly when . So split and by size, transform each piece, combine the pieces whose sizes add up to , and keep only the masks of size (Björklund, Husfeldt, Kaski & Koivisto, 2007):
def subset_convolution(f, g, n): # h(X) = sum of f(A) g(X - A) over A subset of X
N = 1 << n
pc = [bin(X).count('1') for X in range(N)]
fh = [zeta([f[X] if pc[X] == k else 0 for X in range(N)], n) for k in range(n + 1)]
gh = [zeta([g[X] if pc[X] == k else 0 for X in range(N)], n) for k in range(n + 1)]
h = [0] * N
for k in range(n + 1): # pieces whose sizes add up to k
hk = [sum(fh[j][X] * gh[k - j][X] for j in range(k + 1)) for X in range(N)]
hk = mobius(hk, n) # back from sums over subsets
for X in range(N):
if pc[X] == k: # sizes add up only when A and B are disjoint
h[X] = hk[X]
return h zeta transforms, pointwise products and Möbius transforms: in total, against for summing over all splits directly. (zeta and mobius are the bit-by-bit loops.)
Inclusion–exclusion at scale
Why care about , where hides polynomial factors? Because many NP-hard problems over elements have natural dynamic programs, and these transforms bring them down to . The flagship example is graph coloring. A graph is -colorable exactly when its vertex set is covered by independent sets. Inclusion–exclusion over the vertices left uncovered counts such covers:
where is the number of independent sets inside (the empty set included). And is one zeta transform.
You want over pairs of disjoint sets with . Why does the plain OR-convolution, , not suffice?
- It is too slow:
- It also counts overlapping pairs with ; tracking sizes, , is what rules them out
- The zeta transform cannot be inverted
- It only works when and are 0/1 functions
Show the answer
B. It also counts overlapping pairs with ; tracking sizes, , is what rules them out
at sums all pairs of subsets of , overlapping or not. Among pairs with , exactly the disjoint ones have , so ranking by size isolates them, at the price of an extra factor .
Key takeaways
s = (s - 1) & mdecrements a counter over the set bits of , so it lists all submasks once, in decreasing order;(s + 1) | mwalks supersets upward.- All submasks of all masks number exactly , which makes partition DPs with the lowest-item trick run in , practical up to –.
- Gosper's hack steps through all masks with ones in increasing order using a few word operations.
- The zeta transform computes sums over subsets in additions; it turns OR-convolution into pointwise products, and with ranking by size gives the subset convolution in .
- Inclusion–exclusion with these transforms colors graphs in ; beating for coloring or general TSP is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For a non-zero submask of , what is (s - 1) & m?
- The next larger submask of
- with its lowest set bit cleared
- The next smaller submask of in numeric order
- The complement of within
Show the answer
C. The next smaller submask of in numeric order
It is a decrement in compressed coordinates: the lowest set bit of is cleared and every lower bit of is set. Clearing the lowest bit alone would skip submasks, such as followed directly by , missing .
Why does enumerating the submasks of every mask of bits take time?
- Each of the masks has about submasks on average
- Each element is independently outside , in , or in : three states per element
- Each submask is visited three times
- It does not: it takes
Show the answer
B. Each element is independently outside , in , or in : three states per element
Pairs correspond to strings in , so there are exactly of them, and the submask loop spends on each. Equivalently, .
Starting from x = 0b0111 with , which mask does Gosper's hack produce next?
Show the answer
B.
The block (, ) moves its top 1 up and drops the other two ones to the bottom: . It is the smallest number above 7 with three set bits.
In min_partition_cost, the group chosen for mask must contain 's lowest item. What would go wrong if any non-empty submask were allowed?
- The answer would be wrong: some partitions would never be considered
- Nothing would break: the same minimum comes out, but each partition into groups is reached in orders, wasting work
- The loop would never terminate
- The running time would drop to
Show the answer
B. Nothing would break: the same minimum comes out, but each partition into groups is reached in orders, wasting work
Minimizing over more choices cannot change a minimum that is already reachable, so the answer stays correct. But every partition can then be built by removing its groups in any order. Fixing the group of the lowest item picks one canonical order, and only submasks containing that item are tried, which also cuts the work. For counting partitions, the canonical choice is essential: without it each partition would be counted times.
Further reading
- M. Beeler, R. W. Gosper & R. Schroeppel, "HAKMEM," MIT Artificial Intelligence Laboratory Memo 239 (1972), item 175.
- A. Björklund, T. Husfeldt, P. Kaski & M. Koivisto, "Fourier meets Möbius: fast subset convolution," Proceedings of STOC (2007).
- A. Björklund, T. Husfeldt & M. Koivisto, "Set partitioning via inclusion–exclusion," SIAM Journal on Computing 39(2) (2009), 546–563.
- M. Cygan, H. Dell, D. Lokshtanov, D. Marx, J. Nederlof, Y. Okamoto, R. Paturi, S. Saurabh & M. Wahlström, "On problems as hard as CNF-SAT," ACM Transactions on Algorithms 12(3) (2016).
- F. V. Fomin & D. Kratsch, Exact Exponential Algorithms (Springer, 2010).