Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 215⋅215≈1092^{15}\cdot2^{15}\approx10^9 steps. It is 315≈1.4×1073^{15}\approx1.4\times10^7, 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, n 2n−1n\,2^{n-1} 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 s←(s−1)&ms\leftarrow(s-1)\mathbin{\&}m, and prove that it visits each exactly once, in decreasing order.
  • Prove that enumerating all submasks of all masks costs Θ(3n)\Theta(3^n), and use it for dynamic programming over set partitions.
  • Generate all kk-subsets in increasing order with Gosper's hack, and derive why it works.
  • Compute sums over subsets in O(n 2n)O(n\,2^n), OR-convolutions, and the subset convolution in O(n22n)O(n^2 2^n), and connect them to O∗(2n)O^*(2^n) algorithms for NP-hard problems.

Walking the submasks of a mask

A submask of mm is a mask ss with s&m=ss\mathbin{\&}m=s: the subset s⊆ms\subseteq m. If mm has kk set bits it has 2k2^k submasks, and testing all 2n2^n masks to find them wastes time when kk is small. The standard loop jumps straight from one submask to the next:

python
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 mm within nn bits are walked upward the same way: s = (s + 1) | m while s < 1 << n.

DerivationWhy the loop visits every submask once, in decreasing order
  1. φ(s)=∑j=0k−1[bit pj of s] 2j\varphi(s)=\sum_{j=0}^{k-1}\big[\text{bit }p_j\text{ of }s\big]\,2^j

    Let the set bits of mm be at positions p0<p1<⋯<pk−1p_0<p_1<\dots<p_{k-1}. Reading a submask's bits at those positions gives a kk-bit number, and this compression is an order-preserving bijection from the submasks of mm onto 0..2k−10..2^k-1:

  2. (s−1)&m  =  s−2pj+∑t<j2pt(s-1)\mathbin{\&}m\;=\;s-2^{p_j}+\sum_{t<j}2^{p_t}

    Let s≠0s\ne0 have its lowest set bit at pjp_j. Subtracting 1 clears that bit and sets every lower bit; masking with mm keeps, among the lower bits, exactly p0,…,pj−1p_0,\dots,p_{j-1}:

  3. φ((s−1)&m)=φ(s)−1\varphi\big((s-1)\mathbin{\&}m\big)=\varphi(s)-1

    In compressed coordinates that is the borrow of an ordinary decrement: bit jj becomes 0 and bits 0..j−10..j-1 become 1. So the loop counts φ\varphi down from φ(m)=2k−1\varphi(m)=2^k-1 to φ(0)=0\varphi(0)=0, visiting every submask exactly once.

Predict before you look

How many masks does the loop visit for m=101102m=10110_2, counting mm itself and 00?

Show the answer

8

mm has three set bits, so it has 23=82^3=8 submasks: the compressed counter runs 111,110,…,000111,110,\dots,000. The other 32−8=2432-8=24 five-bit masks are never touched.

The 3ⁿ bound, and DP over partitions

nn2n2^n masks3n3^n pairs s⊆ms\subseteq m4n4^n pairs of masks
101,02459,049≈1.0×106\approx1.0\times10^6
1532,768≈1.4×107\approx1.4\times10^7≈1.1×109\approx1.1\times10^9
18262,144≈3.9×108\approx3.9\times10^8≈6.9×1010\approx6.9\times10^{10}
20≈1.0×106\approx1.0\times10^6≈3.5×109\approx3.5\times10^9≈1.1×1012\approx1.1\times10^{12}
Testing every pair of masks for s⊆ms\subseteq m costs 4n4^n; the submask loop costs 3n3^n. With the rule of thumb of 10810^8 simple operations per second, 3n3^n algorithms fit up to n≈16n\approx16–1717.

The classic use is dynamic programming over set partitions: split nn items into groups, where a group ss costs cost[s]\mathit{cost}[s], minimizing the total. For each mask mm, choose the group that contains mm's lowest item; that canonical choice counts each partition once instead of once per ordering of its groups.

python
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]

O(3n)O(3^n) time and O(2n)O(2^n) memory, against the Bell number BnB_n of partitions for brute force (B15≈1.4×109B_{15}\approx1.4\times10^9). Typical uses: grouping people into teams, covering items with bundles, and the natural DP for graph coloring.

Check your understanding

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?

  1. Same: both visit each pair s⊆ms\subseteq m once
  2. It costs Θ(4n)\Theta(4^n) instead of Θ(3n)\Theta(3^n): it tests every pair of masks, most of which fail
  3. It costs Θ(2n)\Theta(2^n)
  4. It costs Θ(n 4n)\Theta(n\,4^n)
Show the answer

B. It costs Θ(4n)\Theta(4^n) instead of Θ(3n)\Theta(3^n): it tests every pair of masks, most of which fail

The inner loop runs 2n2^n times for every mm, so 4n4^n tests in all, of which only 3n3^n succeed. For n=15n=15: about 1.1×1091.1\times10^9 tests instead of 1.4×1071.4\times10^7 useful steps.

Gosper's hack: every k-subset in order

To visit only the subsets of size exactly kk, there are (nk)\binom{n}{k} 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:

python
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;.

DerivationWhy the next combination comes out
  1. x=y 0 1a0b⟶x′=y 1 0b+11a−1x=y\,0\,1^a0^b\qquad\longrightarrow\qquad x'=y\,1\,0^{b+1}1^{a-1}

    Write xx with its lowest block of a≥1a\ge1 ones followed by b≥0b\ge0 zeros, under a prefix yy. The next larger number with the same popcount moves the block's top 1 up one place and drops the other a−1a-1 ones to the very bottom:

  2. r=x+c=y 1 0a+br=x+c=y\,1\,0^{a+b}

    The lowest set bit is c=2bc=2^b, and adding it carries through the whole block:

  3. r⊕x=1a+10b⟹⌊(r⊕x)≫2c⌋=1a−1r\oplus x=1^{a+1}0^b\qquad\Longrightarrow\qquad\Big\lfloor\frac{(r\oplus x)\gg2}{c}\Big\rfloor=1^{a-1}

    The XOR marks the bits that changed, a+1a+1 ones above bb zeros. Shifting right by 2 and dividing by c=2bc=2^b leaves ⌊(2a+1−1)/4⌋=2a−1−1\lfloor(2^{a+1}-1)/4\rfloor=2^{a-1}-1, exactly a−1a-1 ones at the bottom:

  4. x′=r∣1a−1=y 1 0b+11a−1x'=r\mid1^{a-1}=y\,1\,0^{b+1}1^{a-1}

    OR-ing them into rr gives x′x'. For example x=10111002x=1011100_2: c=1002c=100_2, r=11000002r=1100000_2, r⊕x=01111002r\oplus x=0111100_2; shifted right by 2 that is 11112=151111_2=15, and 1515 divided by c=4c=4 is 3=1123=11_2, so x′=11000112x'=1100011_2.

Sums over subsets and subset convolution

The sum over subsets (zeta transform) F(X)=∑Y⊆Xf(Y)F(X)=\sum_{Y\subseteq X}f(Y) could be computed with the submask loop in 3n3^n steps. Treating the hypercube one dimension at a time, as in 2-D Prefix Sums & Inclusion–Exclusion, does it in n 2n−1n\,2^{n-1} additions. Here is why the bit-by-bit loop is correct:

DerivationThe invariant of the zeta transform
  1. Fi(X)=∑{ f(Y): Y⊆X,  Y∩{i,…,n−1}=X∩{i,…,n−1} }F_i(X)=\sum\big\{\,f(Y):\ Y\subseteq X,\ \ Y\cap\{i,\dots,n-1\}=X\cap\{i,\dots,n-1\}\,\big\}

    Process bits 0,1,…,n−10,1,\dots,n-1 in turn; for bit ii, every mask XX containing ii does F(X)+=F(X∖{i})F(X)\mathrel{+}=F(X\setminus\{i\}). Claim: after bits 0..i−10..i-1 are processed, F(X)F(X) sums ff over the subsets of XX that agree with XX on all bits ≥i\ge i:

  2. Fi+1(X)=Fi(X)+Fi(X∖{i})(i∈X)F_{i+1}(X)=F_i(X)+F_i\big(X\setminus\{i\}\big)\qquad(i\in X)

    Initially (i=0i=0) only Y=XY=X qualifies. Processing bit ii: if i∉Xi\notin X nothing changes and nothing should. If i∈Xi\in X, the qualifying YY for Fi+1(X)F_{i+1}(X) either contain ii, counted in Fi(X)F_i(X), or do not, counted in Fi(X∖{i})F_i(X\setminus\{i\}):

  3. Fn(X)=∑Y⊆Xf(Y),f(X)=∑Y⊆X(−1)∣X∖Y∣F(Y)F_n(X)=\sum_{Y\subseteq X}f(Y),\qquad f(X)=\sum_{Y\subseteq X}(-1)^{\abs{X\setminus Y}}F(Y)

    After all nn bits the agreement condition is empty, so Fn=ζfF_n=\zeta f. 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 h(X)=∑A∪B=Xf(A)g(B)h(X)=\sum_{A\cup B=X}f(A)g(B), a pair (A,B)(A,B) is counted in ζh(X)\zeta h(X) exactly when both AA and BB are subsets of XX, so ζh=ζf⋅ζg\zeta h=\zeta f\cdot\zeta g, and h=μ(ζf⋅ζg)h=\mu(\zeta f\cdot\zeta g) in O(n 2n)O(n\,2^n).

The subset convolution wants disjoint pairs: h(X)=∑A⊆Xf(A) g(X∖A)h(X)=\sum_{A\subseteq X}f(A)\,g(X\setminus A). Disjointness is invisible to ζ\zeta, but sizes reveal it: A∪B=XA\cup B=X and ∣A∣+∣B∣=∣X∣\abs{A}+\abs{B}=\abs{X} hold together exactly when A∩B=∅A\cap B=\emptyset. So split ff and gg by size, transform each piece, combine the pieces whose sizes add up to kk, and keep only the masks of size kk (Björklund, Husfeldt, Kaski & Koivisto, 2007):

python
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

2(n+1)2(n+1) zeta transforms, O(n22n)O(n^2 2^n) pointwise products and n+1n+1 Möbius transforms: O(n22n)O(n^2 2^n) in total, against 3n3^n for summing over all splits directly. (zeta and mobius are the bit-by-bit loops.)

Inclusion–exclusion at scale

Why care about O∗(2n)O^*(2^n), where O∗O^* hides polynomial factors? Because many NP-hard problems over nn elements have natural 3n3^n dynamic programs, and these transforms bring them down to 2n2^n. The flagship example is graph coloring. A graph is kk-colorable exactly when its vertex set VV is covered by kk independent sets. Inclusion–exclusion over the vertices left uncovered counts such covers:

ck=∑X⊆V(−1)∣V∖X∣ i(X)k,c_k=\sum_{X\subseteq V}(-1)^{\abs{V\setminus X}}\,i(X)^k,

where i(X)i(X) is the number of independent sets inside XX (the empty set included). And i=ζ(indicator of independent sets)i=\zeta(\text{indicator of independent sets}) is one zeta transform.

Check your understanding

You want ∑f(A) g(B)\sum f(A)\,g(B) over pairs of disjoint sets with A∪B=XA\cup B=X. Why does the plain OR-convolution, μ(ζf⋅ζg)\mu(\zeta f\cdot\zeta g), not suffice?

  1. It is too slow: O(3n)O(3^n)
  2. It also counts overlapping pairs with A∪B=XA\cup B=X; tracking sizes, ∣A∣+∣B∣=∣X∣\abs{A}+\abs{B}=\abs{X}, is what rules them out
  3. The zeta transform cannot be inverted
  4. It only works when ff and gg are 0/1 functions
Show the answer

B. It also counts overlapping pairs with A∪B=XA\cup B=X; tracking sizes, ∣A∣+∣B∣=∣X∣\abs{A}+\abs{B}=\abs{X}, is what rules them out

ζf⋅ζg\zeta f\cdot\zeta g at XX sums all pairs of subsets of XX, overlapping or not. Among pairs with A∪B=XA\cup B=X, exactly the disjoint ones have ∣A∣+∣B∣=∣X∣\abs{A}+\abs{B}=\abs{X}, so ranking by size isolates them, at the price of an extra factor n2n^2.

Key takeaways

  • s = (s - 1) & m decrements a counter over the set bits of mm, so it lists all 2∣m∣2^{\abs{m}} submasks once, in decreasing order; (s + 1) | m walks supersets upward.
  • All submasks of all masks number exactly 3n3^n, which makes partition DPs with the lowest-item trick run in O(3n)O(3^n), practical up to n≈16n\approx16–1717.
  • Gosper's hack steps through all (nk)\binom{n}{k} masks with kk ones in increasing order using a few word operations.
  • The zeta transform computes sums over subsets in n 2n−1n\,2^{n-1} additions; it turns OR-convolution into pointwise products, and with ranking by size gives the subset convolution in O(n22n)O(n^2 2^n).
  • Inclusion–exclusion with these transforms colors graphs in O∗(2n)O^*(2^n); beating 2n2^n 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.

Question 1

For a non-zero submask ss of mm, what is (s - 1) & m?

  1. The next larger submask of mm
  2. ss with its lowest set bit cleared
  3. The next smaller submask of mm in numeric order
  4. The complement of ss within mm
Show the answer

C. The next smaller submask of mm in numeric order

It is a decrement in compressed coordinates: the lowest set bit of ss is cleared and every lower bit of mm is set. Clearing the lowest bit alone would skip submasks, such as 1010010100 followed directly by 1000010000, missing 1001010010.

Question 2

Why does enumerating the submasks of every mask of nn bits take Θ(3n)\Theta(3^n) time?

  1. Each of the 2n2^n masks has about 1.5n1.5^n submasks on average
  2. Each element is independently outside mm, in m∖sm\setminus s, or in ss: three states per element
  3. Each submask is visited three times
  4. It does not: it takes Θ(4n)\Theta(4^n)
Show the answer

B. Each element is independently outside mm, in m∖sm\setminus s, or in ss: three states per element

Pairs s⊆ms\subseteq m correspond to strings in {0,1,2}n\{0,1,2\}^n, so there are exactly 3n3^n of them, and the submask loop spends O(1)O(1) on each. Equivalently, ∑k(nk)2k=3n\sum_k\binom{n}{k}2^k=3^n.

Question 3

Starting from x = 0b0111 with n=5n=5, which mask does Gosper's hack produce next?

  1. 01000201000_2
  2. 01011201011_2
  3. 10011210011_2
  4. 01111201111_2
Show the answer

B. 01011201011_2

The block 111111 (a=3a=3, b=0b=0) moves its top 1 up and drops the other two ones to the bottom: 01011201011_2. It is the smallest number above 7 with three set bits.

Question 4

In min_partition_cost, the group ss chosen for mask mm must contain mm's lowest item. What would go wrong if any non-empty submask were allowed?

  1. The answer would be wrong: some partitions would never be considered
  2. Nothing would break: the same minimum comes out, but each partition into gg groups is reached in g!g! orders, wasting work
  3. The loop would never terminate
  4. The running time would drop to O(2n)O(2^n)
Show the answer

B. Nothing would break: the same minimum comes out, but each partition into gg groups is reached in g!g! 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 g!g! 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).