Lesson 23 · Problem-solving methods

Bitmask Dynamic Programming

Bitmask DP is dynamic programming where the state is a subset of a small set, stored as the bits of one integer. It replaces trying every order (n!) with one entry per subset (2ⁿ), which works up to about 20 items.

Bitmask Dynamic Programming concept diagramA visual explanation of the layout and operations shown in this lesson.one integer names the visited set — bit i is city i1bit 30bit 21bit 11bit 0mask 1011 = {0, 1, 3} visited · 2 still opendp[mask][u]add vmask | 1<<vdp[new][v]2ⁿ masks × n ends — the subset itself is the dimension being iterated
1

What Bitmask DP Is

Bitmask DP is dynamic programming whose state is a subset. With n items, bit i of an integer says whether item i is in the subset, so the 2ⁿ subsets are just the integers 0 to 2ⁿ − 1 and can index an array directly.

It fits problems that ask for the best way to use, visit or assign every item of a small set: assign n workers to n jobs, visit every city once, split items into groups. Trying every order costs n!; bitmask dynamic programming keeps one answer per subset instead, which is why it is also called DP over subsets.

The bit operations come from bit manipulation: mask & (1 << i) tests item i, mask | (1 << i) adds it, and popcount(mask) counts how many items are already used.

  • One integer = one subset
  • Fits n up to about 20
2

Choosing the State

  1. Ask what the rest of the problem depends on
  2. If it is only the set of items used, the state is dp[mask]
  3. If it also needs the last item, use dp[mask][last]
  4. Write the move that adds one item, and the starting mask

The key question is whether two partial solutions with the same used set behave the same from here on. In job assignment they do: once jobs 0 and 1 are taken by the first two workers, the remaining choices do not care who took which. So dp[mask] is the cheapest way to give the jobs in mask to the first popcount(mask) workers, and the next worker is popcount(mask).

When the future also depends on where you stopped, add that to the state. A route that has visited the same cities but ends at a different one has different onward costs, so route problems use dp[mask][last]; the travelling salesman problem and Hamiltonian path lessons build that table.

  • Same used set, same future → one state
  • Add the last item only when it changes the future
3

Worked Example: Assigning Jobs

Three workers and three jobs, with cost[w][j] = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]. Start with dp[000] = 0. From each mask, worker popcount(mask) tries every job whose bit is still 0: dp[mask | 1 << j] = min(dp[mask | 1 << j], dp[mask] + cost[w][j]).

Mask 011 is reached two ways: worker 0 on job 0 and worker 1 on job 1 (9 + 4 = 13), or the other way round (2 + 6 = 8). The table keeps 8 and forgets 13. That merge is where the saving comes from. The full mask 111 ends at 9: worker 0 takes job 1, worker 1 job 0, worker 2 job 2.

Greedy fails here: worker 0 takes its cheapest job (2), worker 1 its cheapest free job (3), and worker 2 is stuck with 5, for 10. The tracer shows each move.

  • Masks only grow, so plain numeric order is a safe loop order
  • Store the move that set each value to recover the assignment
Key reference

Terms, operations, and practical uses

Bits

  • MaskAn integer whose bit i is 1 when item i is in the subset. With n items it ranges over 0 to 2ⁿ − 1.
  • Full mask(1 << n) − 1, every item used. The answer usually sits at dp[full] or dp[full][last].
  • PopcountNumber of set bits. Tells how many items are used, so it can stand in for a worker or position index.

States and moves

  • dp[mask]Best value for the used set alone. Enough when the future does not depend on which item came last.
  • dp[mask][last]Adds the last item, needed for routes where the next step's cost depends on where you are.
  • Adding an itemFrom mask, choose j with bit j clear and move to mask | (1 << j). The new mask is always larger.

Costs

  • O(n · 2ⁿ)Time for dp[mask] with n moves per mask. About 21 million steps at n = 20.
  • Submask loopsub = (sub − 1) & mask lists every submask; across all masks the total is 3ⁿ.
  • SOS DPSum over subsets: aggregates over every submask of every mask in O(n · 2ⁿ).
Implementation

Code in Python, C++ and Java

cost = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]
n = len(cost)
INF = float("inf")
dp = [INF] * (1 << n)
job = [-1] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
    if dp[mask] == INF:
        continue
    w = bin(mask).count("1")
    if w == n:
        continue
    for j in range(n):
        if mask & (1 << j) == 0:
            nxt = mask | (1 << j)
            if dp[mask] + cost[w][j] < dp[nxt]:
                dp[nxt] = dp[mask] + cost[w][j]
                job[nxt] = j
full = (1 << n) - 1
print("Minimum cost:", dp[full])
mask, picks = full, []
while mask:
    j = job[mask]
    mask ^= 1 << j
    picks.append(j)
for w, j in enumerate(reversed(picks)):
    print(f"worker {w} -> job {j}")
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int>> cost = {{9, 2, 7}, {6, 4, 3}, {5, 8, 1}};
    int n = cost.size();
    const int INF = 1e9;
    vector<int> dp(1 << n, INF), job(1 << n, -1);
    dp[0] = 0;
    for (int mask = 0; mask < (1 << n); mask++) {
        if (dp[mask] == INF) continue;
        int w = __builtin_popcount(mask);
        if (w == n) continue;
        for (int j = 0; j < n; j++) {
            if ((mask & (1 << j)) == 0) {
                int nxt = mask | (1 << j);
                if (dp[mask] + cost[w][j] < dp[nxt]) {
                    dp[nxt] = dp[mask] + cost[w][j];
                    job[nxt] = j;
                }
            }
        }
    }
    int full = (1 << n) - 1;
    cout << "Minimum cost: " << dp[full] << '\n';
    vector<int> picks;
    for (int mask = full; mask; mask ^= 1 << job[mask]) picks.push_back(job[mask]);
    for (int w = 0; w < n; w++) cout << "worker " << w << " -> job " << picks[n - 1 - w] << '\n';
}
import java.util.*;

class Main {
    public static void main(String[] args) {
        int[][] cost = {{9, 2, 7}, {6, 4, 3}, {5, 8, 1}};
        int n = cost.length;
        final int INF = 1_000_000_000;
        int[] dp = new int[1 << n], job = new int[1 << n];
        Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int mask = 0; mask < (1 << n); mask++) {
            if (dp[mask] == INF) continue;
            int w = Integer.bitCount(mask);
            if (w == n) continue;
            for (int j = 0; j < n; j++) {
                if ((mask & (1 << j)) == 0) {
                    int nxt = mask | (1 << j);
                    if (dp[mask] + cost[w][j] < dp[nxt]) {
                        dp[nxt] = dp[mask] + cost[w][j];
                        job[nxt] = j;
                    }
                }
            }
        }
        int full = (1 << n) - 1;
        System.out.println("Minimum cost: " + dp[full]);
        List<Integer> picks = new ArrayList<>();
        for (int mask = full; mask != 0; mask ^= 1 << job[mask]) picks.add(job[mask]);
        for (int w = 0; w < n; w++) System.out.println("worker " + w + " -> job " + picks.get(n - 1 - w));
    }
}
Watch it run

Step through it

Running on cost = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]

assign 3 workers to 3 jobs, one job eachcostjob 0job 1job 2w0927w1643w2581worker 0 nextworker 1 nextworker 2 nextall placed0000001∞010∞100∞011∞101∞110∞111∞dp[mask] = cheapest cost of giving the jobs in mask to the first popcount(mask) workers8 masks in all; every other entry starts at ∞dp[000] = 0
Step 1

Masks for three jobs

Bit j of the mask says job j is taken, with job 0 as the rightmost bit, so 101 means jobs 0 and 2. Workers are placed in order, so the number of set bits also says which worker comes next. Only the empty mask has a cost so far: 0.

Output
1 / 10
4

Time and Memory

Masks only gain bits, so every predecessor of a mask is a smaller number and the loop for mask in 0 .. 2ⁿ − 1 visits them first. dp[mask] needs O(2ⁿ) memory and O(n · 2ⁿ) time; dp[mask][last] needs O(n · 2ⁿ) memory and O(n² · 2ⁿ) time.

Memory often runs out before time. dp[mask][last] with n = 20 and 4-byte values is 20 × 2²⁰ × 4 bytes, about 84 MB; n = 25 would need over 3 GB. When the work only depends on popcount, drop the extra dimension.

Trying every order vs one entry per subset
nOrders (n!)dp[mask] moves (n · 2ⁿ)
103,628,80010,240
202.4 × 10¹⁸about 21 million
251.6 × 10²⁵about 839 million
  • Numeric order works because adding a bit makes the number bigger
  • Size the table before you allocate it
5

Submask Enumeration

Some problems move from a mask to any part of it, for example splitting items into groups where dp[mask] tries every group sub ⊆ mask. The loop sub = mask; while sub > 0: ...; sub = (sub − 1) & mask visits every non-empty submask of mask in decreasing order and nothing else. Subtracting 1 clears the lowest set bit and sets the bits below it; the & keeps only bits that belong to mask.

Over all masks this costs O(3ⁿ), not 4ⁿ: for each item there are three cases (not in mask, in mask but not in sub, in both). At n = 15 that is about 14 million steps. Handle sub = 0 separately if the recurrence needs it, since the loop stops before it.

When the task is a sum over all submasks of every mask, SOS DP (sum over subsets) does it in O(n · 2ⁿ) by adding one bit dimension at a time.

  • (sub − 1) & mask steps to the next smaller submask
  • All mask and submask pairs: 3ⁿ
6

Common Bugs and Edge Cases

Operator precedence. In C and C++, mask & 1 << j == 0 parses as mask & ((1 << j) == 0); Java rejects it outright. Bracket every bit test: (mask & (1 << j)) == 0. Use 1L << j or 1LL << j once n can reach 31.

Worker not tied to the mask. If the code tries every worker from every mask, one worker can take two jobs; in the worked example this reports 8, a cost that no valid assignment has. Take the worker from popcount(mask), or add it to the state.

Complements. ~mask sets every high bit too. Use full ^ mask with full = (1 << n) − 1 to get the unused items.

Test n = 0 and n = 1, an infinity value that does not overflow when a cost is added, and compare with a brute force over all n! orders for n up to 7.

  • Bracket every bit test
  • Complement with full ^ mask, not ~mask
  • Check against brute force for small n