Dynamic Programming · Pattern 11 of 12
Bitmask DP: a subset as the state
When n is small (about 20 or less), store "which items are already used" as the bits of an integer. dp[mask] is the best answer for that subset, built from a smaller mask with one item or one group removed.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- n is tiny (n <= 16 or 20) and the order or grouping of items matters
- Assign items to workers, sessions or teams
- Cover a small set of required skills or letters
The template
// Work Sessions: dp[mask] = {sessions used, time used in the last session}, the smaller the better
int minSessions(int[] tasks, int sessionTime) {
int n = tasks.length, full = 1 << n;
int[][] dp = new int[full][];
dp[0] = new int[]{1, 0}; // one open, empty session
for (int mask = 1; mask < full; mask++) {
dp[mask] = new int[]{n + 1, 0};
for (int i = 0; i < n; i++) {
if ((mask >> i & 1) == 0) continue;
int[] p = dp[mask ^ (1 << i)]; // task i is the one done last
int[] cand = p[1] + tasks[i] <= sessionTime
? new int[]{p[0], p[1] + tasks[i]} // fits in the open session
: new int[]{p[0] + 1, tasks[i]}; // start a new session
if (cand[0] < dp[mask][0] || (cand[0] == dp[mask][0] && cand[1] < dp[mask][1])) dp[mask] = cand;
}
}
return dp[full - 1][0];
}
// Minimum Time to Finish All Jobs: the w-th worker takes a submask of what is left
int minimumTimeRequired(int[] jobs, int k) {
int n = jobs.length, full = 1 << n;
int[] sum = new int[full]; // sum[mask] = total time of the jobs in mask
for (int mask = 1; mask < full; mask++)
sum[mask] = sum[mask & (mask - 1)] + jobs[Integer.numberOfTrailingZeros(mask)];
int[] dp = sum.clone(); // one worker does everything in mask
for (int w = 2; w <= k; w++) {
int[] next = new int[full];
for (int mask = 0; mask < full; mask++) {
next[mask] = dp[mask];
for (int sub = mask; sub > 0; sub = (sub - 1) & mask) // every submask
next[mask] = Math.min(next[mask], Math.max(dp[mask ^ sub], sum[sub]));
}
dp = next;
}
return dp[full - 1];
} def min_sessions(tasks, session_time):
n = len(tasks)
full = 1 << n
dp = [(n + 1, 0)] * full # (sessions used, time used in the last one)
dp[0] = (1, 0) # one open, empty session
for mask in range(1, full):
for i in range(n):
if mask >> i & 1:
s, used = dp[mask ^ (1 << i)] # task i is the one done last
cand = (s, used + tasks[i]) if used + tasks[i] <= session_time else (s + 1, tasks[i])
dp[mask] = min(dp[mask], cand) # tuples compare sessions first, then time
return dp[full - 1][0]
def minimum_time_required(jobs, k):
n = len(jobs)
full = 1 << n
total = [0] * full # total[mask] = time of the jobs in mask
for mask in range(1, full):
low = (mask & -mask).bit_length() - 1
total[mask] = total[mask & (mask - 1)] + jobs[low]
dp = total[:] # one worker does everything in mask
for _ in range(k - 1):
nxt = dp[:]
for mask in range(full):
sub = mask
while sub: # the new worker takes sub
nxt[mask] = min(nxt[mask], max(dp[mask ^ sub], total[sub]))
sub = (sub - 1) & mask
dp = nxt
return dp[full - 1] // Work Sessions: dp[mask] = {sessions used, time used in the last session}, the smaller the better
int minSessions(vector<int>& tasks, int sessionTime) {
int n = tasks.size(), full = 1 << n;
vector<pair<int, int>> dp(full, {n + 1, 0});
dp[0] = {1, 0}; // one open, empty session
for (int mask = 1; mask < full; mask++)
for (int i = 0; i < n; i++) {
if (!(mask >> i & 1)) continue;
auto [s, used] = dp[mask ^ (1 << i)]; // task i is the one done last
pair<int, int> cand = used + tasks[i] <= sessionTime
? make_pair(s, used + tasks[i]) : make_pair(s + 1, tasks[i]);
dp[mask] = min(dp[mask], cand); // pairs compare sessions first, then time
}
return dp[full - 1].first;
}
// Minimum Time to Finish All Jobs: the w-th worker takes a submask of what is left
int minimumTimeRequired(vector<int>& jobs, int k) {
int n = jobs.size(), full = 1 << n;
vector<int> sum(full, 0); // sum[mask] = total time of the jobs in mask
for (int mask = 1; mask < full; mask++)
sum[mask] = sum[mask & (mask - 1)] + jobs[__builtin_ctz(mask)];
vector<int> dp = sum; // one worker does everything in mask
for (int w = 2; w <= k; w++) {
vector<int> next = dp;
for (int mask = 0; mask < full; mask++)
for (int sub = mask; sub > 0; sub = (sub - 1) & mask) // every submask
next[mask] = min(next[mask], max(dp[mask ^ sub], sum[sub]));
dp = next;
}
return dp[full - 1];
} // Work Sessions: dp[mask] = [sessions used, time used in the last session], the smaller the better
function minSessions(tasks, sessionTime) {
const n = tasks.length, full = 1 << n;
const dp = new Array(full).fill(null).map(() => [n + 1, 0]);
dp[0] = [1, 0]; // one open, empty session
for (let mask = 1; mask < full; mask++)
for (let i = 0; i < n; i++) {
if (!((mask >> i) & 1)) continue;
const [s, used] = dp[mask ^ (1 << i)]; // task i is the one done last
const cand = used + tasks[i] <= sessionTime ? [s, used + tasks[i]] : [s + 1, tasks[i]];
if (cand[0] < dp[mask][0] || (cand[0] === dp[mask][0] && cand[1] < dp[mask][1])) dp[mask] = cand;
}
return dp[full - 1][0];
}
// Minimum Time to Finish All Jobs: the w-th worker takes a submask of what is left
function minimumTimeRequired(jobs, k) {
const n = jobs.length, full = 1 << n, sum = new Array(full).fill(0);
for (let mask = 1; mask < full; mask++)
sum[mask] = sum[mask & (mask - 1)] + jobs[31 - Math.clz32(mask & -mask)];
let dp = [...sum]; // one worker does everything in mask
for (let w = 2; w <= k; w++) {
const next = [...dp];
for (let mask = 0; mask < full; mask++)
for (let sub = mask; sub > 0; sub = (sub - 1) & mask) // every submask
next[mask] = Math.min(next[mask], Math.max(dp[mask ^ sub], sum[sub]));
dp = next;
}
return dp[full - 1];
} The variations
-
1Pack items into bins or workers
Either add one item at a time (
dp[mask]remembers the sessions used and the load of the open one), or give a whole submask to the next worker:dp[w][mask] = min over sub of max(dp[w - 1][mask ^ sub], sum[sub]), which costs O(3ⁿ). Account Balancing counts the most groups whose net debt is zero.Now you solve -
2Cover a set of requirements
The mask is the set of skills (or letters) covered so far. Each person ORs their skills into the mask;
dp[mask]keeps the smallest team that reaches it. Shortest Supersequences enumerates which letters appear twice and checks that the rest can be ordered.Now you solve
Mistakes to avoid
- Operator precedence:
mask >> i & 1is fine, butmask & 1 << i == 0is not. Add brackets around every bit test. - Looping submasks with
sub >= 0:(0 - 1) & maskismaskagain, so the loop never ends. Stop atsub > 0. - Using bitmask DP when n is 40: 2^40 states is far too many. It is only for very small n.
Lesson done
Next: Combinatorics: count with a formula →Mark it done once you can write the template from memory and you have solved the worked examples yourself.