Sub topic 10
Compact Subset States with Bitmasks
This chapter assumes you can already write a bottom-up DP table and analyze its space in Big-O terms. It also assumes you have read the chapter on removing derivable state dimensions, because the main memory saving here comes from that idea. You should also be comfortable with Python's integer bitwise operators.
Some problems need a state that records which items from a set are already used. Examples are assigning workers to jobs, visiting cities, and covering a set of tasks. Storing that set as a Python set or a tuple of booleans per state costs a lot of memory and makes lookups slow. A bitmask stores the whole subset in one integer. That integer also works directly as an array index.
Encoding a Subset as an Integer
A bitmask is an integer whose bit j is 1 when item j belongs to the subset and 0 when it does not. With n items, every subset maps to exactly one integer in the range 0 to 2^n - 1. A flat list of length 2^n can then hold one DP value per subset, with no hashing and no per-state object overhead.
For three jobs, the mask 0b101 (decimal 5) means jobs 0 and 2 are taken and job 1 is free.
These operations come up in every bitmask DP:
| Operation | Python expression | Meaning | Column |
|---|---|---|---|
| Empty set | `0` | No items chosen | |
| Full set | `(1 << n) - 1` | All `n` items chosen | |
| Test item `j` | `mask & (1 << j)` | Nonzero if `j` is in the set | |
| Add item `j` | `mask \ | (1 << j)` | Set with `j` included |
| Remove item `j` | `mask & ~(1 << j)` | Set with `j` excluded | |
| Size of set | `bin(mask).count('1')` or `mask.bit_count()` | Number of chosen items (`bit_count` needs Python 3.10+) | |
| Lowest set bit | `mask & -mask` | Isolates the smallest chosen item |
The Assignment Problem: Dropping the Worker Dimension
Suppose there are n workers and n jobs, and cost[i][j] is the cost of giving job j to worker i. Each worker gets exactly one job and each job goes to exactly one worker. We want the minimum total cost.
The obvious state is (i, mask): workers 0..i-1 have been assigned, and mask holds the jobs they took. That table has n * 2^n entries.
Look at what the state actually says, though. If workers are assigned in order 0, 1, 2, and so on, and each takes exactly one job, then after i workers exactly i bits of mask are set. So i equals the popcount of mask. The worker index is a function of the mask, which makes it a derivable dimension, and you can remove it. The table shrinks to 2^n entries.
def min_assignment_cost(cost):
n = len(cost)
INF = float('inf')
dp = [INF] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
if dp[mask] == INF:
continue
i = bin(mask).count('1')
if i == n:
continue
for j in range(n):
if not mask & (1 << j):
nxt = mask | (1 << j)
dp[nxt] = min(dp[nxt], dp[mask] + cost[i][j])
return dp[(1 << n) - 1]
cost = [
[9, 2, 7],
[6, 4, 3],
[5, 8, 1],
]
print(min_assignment_cost(cost)) # 9: worker0->job1, worker1->job0, worker2->job2The dp[mask] == INF check skips masks that can never be reached. In this problem every mask is reachable, but the check matters in variants with forbidden assignments.
Why Increasing Mask Order Is Safe
Each transition goes from mask to mask | (1 << j), and j is not already in mask. Setting a new bit always produces a larger integer, so every transition moves from a smaller index to a larger one. When the loop reaches mask, every predecessor of mask has already been processed, so dp[mask] is final. Plain range(1 << n) therefore gives a valid topological order, and you don't need any extra ordering logic.
All masks in one column have the same popcount, so they belong to the same worker. That is the removed dimension, now readable from the mask itself.
How Much Memory This Saves
The table below counts entries and gives an approximate size for a Python list, which stores one 8-byte pointer per entry. Shared or small objects can cost less, and distinct floats cost more.
| n | `2^n` entries | `n * 2^n` entries | List of `2^n` (pointers) | List of `n * 2^n` (pointers) |
|---|---|---|---|---|
| 10 | 1,024 | 10,240 | ~8 KB | ~80 KB |
| 16 | 65,536 | 1,048,576 | ~0.5 MB | ~8 MB |
| 20 | 1,048,576 | 20,971,520 | ~8 MB | ~168 MB |
| 24 | 16,777,216 | 402,653,184 | ~134 MB | ~3.2 GB |
Dropping the worker dimension saves a factor of n. The 2^n term is still there, so bitmask DP is practical up to about n = 20 in Python and about n = 25 in C or C++. Past that size you need a different algorithm. For the assignment problem, that means the Hungarian algorithm, which runs in O(n^3) time.
Time is unchanged by the dimension removal: O(n * 2^n) in both versions, because each mask still tries n jobs.
Shrinking Each Entry
A Python list of floats also stores a separate float object for every distinct value, at about 24 bytes each on CPython. If the values are numbers of known type, a typed array stores them unboxed:
from array import array
def min_assignment_cost_compact(cost):
n = len(cost)
INF = float('inf')
dp = array('d', [INF]) * (1 << n) # 8 bytes per entry, no per-value objects
dp[0] = 0.0
for mask in range(1 << n):
cur = dp[mask]
if cur == INF:
continue
i = bin(mask).count('1')
if i == n:
continue
for j in range(n):
if not mask & (1 << j):
nxt = mask | (1 << j)
cand = cur + cost[i][j]
if cand < dp[nxt]:
dp[nxt] = cand
return dp[(1 << n) - 1]
print(min_assignment_cost_compact([[9, 2, 7], [6, 4, 3], [5, 8, 1]])) # 9.0At n = 20 this uses exactly 8 MB for the table. For integer costs that fit in 32 bits, array('i') halves that to 4 MB.
When a Dimension Cannot Be Dropped
Popcount gave us the worker index only because workers are processed in a fixed order. Compare this with the travelling salesman problem (TSP). There the state is (mask, last), where last is the city you are currently standing in. Two tours can visit the same set of cities and end in different places, and the cost of the next step depends on where you are. You cannot compute last from mask, so the table has to stay at n * 2^n.
The test is the same one used throughout this tutorial. If two states with the same mask can have different futures, the extra component carries information and must stay. If the extra component is fully determined by the mask, remove it.
Common Errors
- Shift overflow in fixed-width languages. In C or Java,
1 << 31on a 32-bitintoverflows, and1 << 32is undefined behavior in C. Use1LL << jor1L << jonce masks can exceed 31 bits. Python integers have no fixed width, so this bug does not appear there. - Off-by-one in the full mask. The full set is
(1 << n) - 1, not1 << n. Indexingdp[1 << n]raises anIndexErrorbecause the list has only1 << nentries. - Assuming popcount gives an order when it doesn't. If the problem lets you process items in any order, or assign several at once, popcount no longer identifies the stage.
- Iterating submasks with nested loops. Some recurrences look at every submask of
mask. The loopsub = (sub - 1) & maskvisits them all, and summed over every mask the total work isO(3^n)rather thanO(4^n):
def submasks(mask):
sub = mask
while sub:
yield sub
sub = (sub - 1) & mask
yield 0
print([bin(s) for s in submasks(0b101)]) # ['0b101', '0b100', '0b1', '0b0']Exercise
In minassignmentcost, the outer loop visits masks in plain increasing numeric order. Explain why dp[mask] is already final when the loop reaches it, even though masks with different popcounts are interleaved (for example 3 = 0b011 comes before 4 = 0b100).
Show answer
Every transition adds a bit that was not set, so it goes from mask to a strictly larger integer. All predecessors of a mask are therefore smaller integers, and the loop has already processed them. The order between masks with different popcounts doesn't matter, because there are never transitions from a larger integer to a smaller one.
Exercise
A variant of the assignment problem has n workers and m jobs with m > n. Each worker takes exactly one job, and some jobs stay unassigned. Can you still drop the worker dimension? What is the table size?
Show answer
Yes. Workers are still assigned in a fixed order, one job each, so the next worker index equals popcount(mask). The mask ranges over subsets of the m jobs, giving 2^m entries. Skip any mask whose popcount exceeds n, and take the answer as the minimum over all masks with exactly n set bits.
Exercise
For TSP with n = 20 cities, estimate the table size in entries and in bytes when each entry is an 8-byte double. Explain why you cannot apply the popcount trick to reduce it.
Show answer
The state is (mask, last), so there are 20 * 2^20 = 20,971,520 entries, or about 168 MB at 8 bytes each. Popcount tells you how many cities have been visited, but not which one you are standing in. Two paths over the same set can end at different cities and have different remaining costs, so last carries real information and must stay.