Sub topic 3
Compact Subset States with Bitmasks
This chapter assumes you know bottom-up tabulation, rolling rows, and Big-O space analysis from the earlier chapters.
Compact Subset States with Bitmasks
Some problems need a state that records which items are already used. A bitmask is an integer whose bit j is 1 when item j is used. In job assignment, the next worker's index equals the number of set bits in the mask. That means you can drop the worker dimension and store only 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]
print(min_assignment_cost([[9, 2, 7], [6, 4, 3], [5, 8, 1]])) # 9Storing Only Reachable States
A dense array wastes space when most states can never occur. A hash map keyed by state stores only the states you actually reach.
def count_subset_sums(nums, target):
ways = {0: 1}
for x in nums:
nxt = dict(ways)
for s, c in ways.items():
nxt[s + x] = nxt.get(s + x, 0) + c
ways = nxt
return ways.get(target, 0)
print(count_subset_sums([1000, 2000000, 3], 1003)) # 1The Hidden Memory Cost of Top-Down Memoization
Memoization keeps every state it visits until the function returns, so you cannot roll rows. Recursion adds stack frames on top of the cache. In Python the default recursion limit is about 1000 calls. Each cache entry is also much larger than an array slot. If the state space is dense, convert to bottom-up.
Getting the Answer Back: Reconstruction After Compression
Rolling arrays keep the optimal value but discard the choices that produced it. You can store the full table, which costs O(mn) space. Or you can store only a compact table of choices, such as one bit per cell. A third option is to recompute the choices.
Hirschberg's Algorithm: Linear Space with Full Reconstruction
For LCS and edit distance, Hirschberg splits string x at its middle. It runs a forward two-row pass on the first half and a backward two-row pass on the second half. The column where the two scores sum to the maximum is the split point for y. It then recurses on both halves. Time stays O(mn), and space drops to O(m + n).
Choosing the Right Reduction for a Recurrence
| Dependency pattern | Technique |
|---|---|
| Last k values | Rolling variables or `i % k` buffer |
| Previous row only | Two rows, or one row with loop direction |
| Previous row plus diagonal | One row plus a `diag` variable |
| Subset of n items | Bitmask, 2^n entries |
| Few reachable states | Hash map |
| Need the solution, not only the value | Choice table or Hirschberg |
Exercise
You compressed LCS to two rows but now must print the subsequence itself in O(m + n) space. Which method do you use, and what does it cost in time?
Show answer
Use Hirschberg's divide-and-conquer. Forward and backward two-row passes find a split point, and recursion rebuilds the full subsequence. Time stays O(mn), roughly double the constant of one pass.