Welcome, future competitive programmer! 🚀 Bitmask DP is where bit manipulation meets dynamic programming. It's the secret weapon for solving subset-based NP-hard problems — partitioning, game theory, load balancing, and more. Here's the deal: Normal DP works on contiguous ranges. But what if your state isn't a range — it's a set of chosen elements? That's where bitmasks come in. Each bit tells you is this element used or not? and BOOM — you can DP over 2ⁿ states like it's nothing.
Imagine you have 4 items with values [3, 7, 2, 5]. You need to pick a subset that maximizes the total value. Sounds easy with 4 items, right? But what about 20 items? That's 2²⁰ = 1,048,576 subsets — way too many to brute force.
Bitmask DP is the answer. Instead of enumerating subsets explicitly, we encode each subset as a bitmask — an integer where bit i is 1 if element i is included, 0 otherwise. Then we DP over masks from 0 to 2ⁿ-1.
Bitmask DP Over Subsets
Tip
💡 The Core Insight: The number of masks (2ⁿ) is huge, but the recurrence is O(n) per mask. So total complexity is O(n × 2ⁿ). For n ≤ 20, that's ~20 million operations — perfectly feasible! For n = 12, it's just 49,152 operations.
1. Bitmask DP Fundamentals — The Recurrence Pattern
Let's build the intuition from the ground up. Every Bitmask DP problem follows the same rhythm:
Note
🎒 Real-World Analogy: Imagine you're packing for a trip with n items, each with a weight and value. Normally, DP works on a contiguous range — like "first i items." But what if you can pick items in ANY order? The state isn't "first i items" but rather "which specific items are already packed." That's a SUBSET — and bitmasks represent subsets perfectly. dp[mask] = the best value achievable using exactly the items in mask, regardless of order!
The Building Blocks
First, let's master the bit operations you'll use constantly:
example.js
// Bit operations for Bitmask DP
// Check if element i is USED (bit i is 1)
(mask & (1 << i)) !== 0
// Check if element i is UNUSED (bit i is 0)
(mask & (1 << i)) === 0
// Mark element i as USED (set bit i to 1)
newMask = mask | (1 << i)
// Mark element i as UNUSED (set bit i to 0)
newMask = mask & ~(1 << i)
// Count used elements (popcount)
function popcount(mask) {
let count = 0;
while (mask) { count += mask & 1; mask >>>= 1; }
return count;
}
// Alternative: built-in
// mask.toString(2).split('1').length - 1
// Iterate over all subsets of a mask
for (let sub = mask; sub; sub = (sub - 1) & mask) {
// process submask
The General DP Template
Every Bitmask DP looks like this skeleton:
🔍 Real-Time Thinking — What Do I Know?
"I need to DP over subsets. Each subset is a mask from 0 to 2ⁿ-1. For each mask, I consider adding each UNUSED element. If I've computed dp[mask] (best value using items in mask), then for each unused element i, dp[mask | (1<<i)] = best(dp[mask | (1<<i)], dp[mask] + value[i]). The outer loop iterates masks in increasing order — this guarantees that when I process a mask, all its subsets have already been processed!"
📋 Edge Cases to Consider
n = 0: Only mask 0 exists. dp[0] = base value. Returns immediately.
n = 1: Only 2 masks (0 and 1). Trivial but tests the base case.
n > 20: 2ⁿ states becomes infeasible. For n=25, ~33 million states. Consider meet-in-the-middle or heuristics.
Unreachable states: Use -Infinity or null as sentinel. Skip unreachable states in the DP loop.
Memory constraints: dp[2ⁿ] for n=20 is ~1 million entries (~8 MB for integers). For n=22, ~32 MB. For 2D dp like TSP (dp[2ⁿ][n]), n=20 would be ~160 MB — too much!
example.js
function bitmaskDP(items) {
const n = items.length;
const totalMasks = 1 << n;
const dp = new Array(totalMasks).fill(-Infinity);
dp[0] = 0; // Base: empty set
for (let mask = 0; mask < totalMasks; mask++) {
// Skip if this state is unreachable
if (dp[mask] === -Infinity) continue;
// Try adding every UNUSED element
for (let i = 0; i < n; i++) {
if ((mask & (1 << i)) === 0) { // element i is unused
const newMask = mask | (1 << i);
const newVal = dp[mask] + items[i];
dp[newMask] = Math.max(dp[newMask], newVal);
}
}
}
// Result depends on problem
return dp[totalMasks - 1]; // full set
Key Insight
🔑 The Magic: The outer loop goes through ALL masks from 0 to 2ⁿ-1. For each mask, we try to add every unused element. Each "add" creates a new mask (bigger subset). This guarantees: ✅ All states are reachable from base ✅ Each state is processed exactly ONCE ✅ We never revisit a smaller state after processing it
When Does Bitmask DP Work?
Constraint
Feasibility
Why?
n ≤ 12
Very Fast
~49K operations, instant
n ≤ 20
Feasible
~20M ops, within 1 second
n ≤ 22
Push It
~92M ops, need optimization
n = 25
Too Slow
~800M ops, need pruning/heuristics
Warning
⚠️ Reality Check: Bitmask DP gives you 2ⁿ states. For n=30, that's 1 billion states — too many for any computer. Always check constraints: n ≤ 20 is the sweet spot. If n is larger, you need a different approach (meet-in-the-middle, greedy, or pruning).
2. Partition to K Equal Sum Subsets — The Bucket Filling Problem
Problem: Given an array of integers, can you partition it into k subsets that each have the same sum?
Example: [4, 3, 2, 3, 5, 2, 1], k=4 → each subset must sum to 5. Can we do it?
Note
📦 Real-World Analogy: Imagine you're packing k identical boxes for a move. Each box has the same weight capacity. You have items of different weights. Can you pack ALL items into the k boxes without exceeding the capacity? This is the partition problem — and it's NP-complete! The trick is to fill boxes greedily: sort items heaviest-first, try to fit each item into a box, and backtrack when it doesn't work.
🤔 Let's Think About It
This is the partition problem — a classic NP-complete problem. There's no polynomial solution. But for small n (≤ 15), we can use backtracking with pruning.
Brute Force: Check All Partitions
The naive approach: generate every possible subset assignment. That'skⁿ possibilities — astronomical even for small n.
✨ Smart Backtracking with Pruning
The key insight: sort descending, then try to fill buckets greedily, backtracking when a bucket can't reach its target.
Partition to K Equal Sum Subsets
example.js
function canPartitionKSubsets(nums, k) {
const total = nums.reduce((a, b) => a + b, 0);
if (total % k !== 0) return false;
const target = total / k;
nums.sort((a, b) => b - a); // Sort descending!
if (nums[0] > target) return false;
const used = new Array(nums.length).fill(false);
function backtrack(startIdx, currentSum, remainingBuckets) {
// All buckets filled!
if (remainingBuckets === 0) return true;
// Current bucket is full → start next bucket
if (currentSum === target)
return backtrack(0, 0, remainingBuckets - 1);
for (let i = startIdx; i < nums.length; i++) {
if (!used[i] && currentSum + nums[i] <= target) {
used[i] = true;
if (backtrack(i + 1, currentSum + nums[i], remainingBuckets))
return true;
used[i] = false;
// 🔥 CRITICAL PRUNE: If this number couldn't fill
// an empty bucket, NO number will!
if (currentSum === 0) return false;
// 🔥 CRITICAL PRUNE: Skip duplicates
while (i + 1 < nums.length && nums[i + 1] === nums[i])
i++;
}
}
return false;
}
return backtrack(0, 0, k);
⚡ Interview Tip: The sort descendingstep is CRITICAL. By trying large numbers first, we either fill buckets quickly or fail fast. If we sorted ascending, we'd waste time with tiny numbers that can't fill a bucket. Also remember the two killer prunes: 1️⃣ "empty bucket skip" — if currentSum===0 and nums[i] doesn't work, nothing will 2️⃣ "duplicate skip" — skip same-valued elements after a failure
PROBLEMPartition to K Equal Sum Subsets
Can you partition an array into k subsets with equal sum? Classic NP-complete problem solved with backtracking + pruning.
Editable example loads when this section enters view.
3. Matchsticks to Square — The 4-Bucket Partition
Problem: You're given matchsticks of different lengths. Can you arrange them to form a square? Each matchstick must be used exactly once. No breaking matchsticks!
🔍 Real-Time Thinking — What Do I Know?
"This is exactly the partition problem with k=4. Each side of the square must sum to total/4. If total isn't divisible by 4, return false immediately. Sort matchsticks descending so I place the longest ones first — they're the most constrained and fail fastest. The pruning rules are crucial: if an empty side fails to fit a matchstick, no other empty side will work either (they're symmetric). And skip duplicate-length matchsticks after a failure."
🤔 Think About It
This is EXACTLY the partition problem with k = 4. The target side length is total / 4. If it's not an integer, return false immediately.
But here's the twist: since k is ALWAYS 4, we can add even more aggressive pruning rules.
Matchsticks to Square — Feasible Assignment. Use [1,1,2,2,2]; total 8 so each of four equal sides is 2. All five matches form a square with side length 2.
example.js
function makesquare(matchsticks) {
const total = matchsticks.reduce((a, b) => a + b, 0);
if (total % 4 !== 0) return false;
const side = total / 4;
matchsticks.sort((a, b) => b - a); // Sort descending!
if (matchsticks[0] > side) return false;
const sides = [0, 0, 0, 0]; // 4 sides of the square
function dfs(idx) {
// All matchsticks used → square formed!
if (idx === matchsticks.length) return true;
for (let s = 0; s < 4; s++) {
if (sides[s] + matchsticks[idx] <= side) {
sides[s] += matchsticks[idx];
if (dfs(idx + 1)) return true;
sides[s] -= matchsticks[idx];
// 🔥 PRUNE: If this side wasn't touched,
// other empty sides won't work either
if (sides[s] === 0) return false;
// 🔥 PRUNE: Skip same-length sides
while (s + 1 < 4 && sides[s] === sides[s + 1])
s++;
}
}
return false;
}
return dfs(0);
Pruning Rules Comparison
Pruning Rule
Why It Works
Savings
Sort descending
Largest constraints first = fail fast
10-100x
sides[s] === 0 after backtrack
If an empty side fails, all empty sides fail
5-10x
Skip same-length sides
Symmetric states are identical
2-5x
side > target
Can't exceed the target side length
Essential
Key Insight
🔑 The Big Picture: Matchsticks to Square is just Partition K = 4 with a fancy name. The same backtracking + pruning pattern works. The key difference: since we always have exactly 4 buckets, we can use the "skip empty sides" prune more aggressively.
PROBLEMMatchsticks to Square
Can you arrange matchsticks to form a square? Each matchstick used exactly once. Backtracking with aggressive pruning.
Editable example loads when this section enters view.
4. Can I Win — Game Theory with Bitmask DP
Problem: Two players take turns picking numbers from 1 to n. Each number can be used once. The first player to reach or exceed a target desiredTotal wins. Assuming both play optimally, can the first player force a win?
Note
♟️ Real-World Analogy: Imagine a game where players take turns picking numbered cards from 1 to n on a table. Each card can only be taken once. The first to reach a total ≥ desiredTotal wins. This is a game of perfect information — both players know all the cards. The key insight: a state is WINNING if there exists SOME move that either wins immediately OR forces the opponent into a LOSING state. And it's LOSING if ALL moves lead to the opponent winning.
🤔 Think About It
This is a game theory problem. Each state is defined by:
Which numbers remain (the bitmask)
Current sum accumulated so far
But wait — can we derive the sum from just the mask? YES! If we know which numbers are used, we know the total sum of used numbers. So the state is just dp[mask].
Can I Win Game Theory with Bitmask DP
example.js
function canIWin(maxChoosableInteger, desiredTotal) {
// Quick sanity checks
const sumAll = maxChoosableInteger * (maxChoosableInteger + 1) / 2;
if (sumAll < desiredTotal) return false;
if (desiredTotal <= 0) return true;
const totalMasks = 1 << maxChoosableInteger;
const memo = new Array(totalMasks).fill(null);
// null = uncomputed, true = win, false = lose
function dp(mask, currentSum) {
// Already computed this state
if (memo[mask] !== null) return memo[mask];
for (let i = 0; i < maxChoosableInteger; i++) {
if ((mask & (1 << i)) === 0) { // number i+1 is unused
const pick = i + 1;
// If we can win immediately, do it!
if (currentSum + pick >= desiredTotal) {
memo[mask] = true;
return true;
}
// If opponent LOSES from this state, we win!
const newMask = mask | (1 << i);
if (!dp(newMask, currentSum + pick)) {
memo[mask] = true;
return true;
}
}
}
// No winning move found → we lose
memo[mask] = false;
return false;
}
return dp(0, 0);
📊 Dry Run — n=4, target=6
Let's trace the game tree. Numbers: {[1, 2, 3, 4]}, each used once. Target sum to win: 6.
Mask
Sum
Player
Options
Result
0000
0
P1
1,2,3,4
Pick 4 → sum=4
1000
4
P2
1,2,3
Pick 3 → sum=7 ≥ 6! P2 wins!
1100
7
P1
—
🛑 P2 already reached target
So if P1 picks 4, P2 can immediately win by picking 3. That's a losing move for P1. Let's check other options...
P1 Pick
P2 Best Response
P1 Wins?
4
3 → wins (3+4=7≥6)
❌
3
4 → wins (4+3=7≥6)
❌
2
4 → wins (4+2=6≥6)
❌
1
4 → sum=5, P1 picks 3 → sum=8≥6 🎉
✅ Pick 1!
Key Insight
🔑 The Game Theory Insight: A state is WINNING if there exists a move that reaches the target OR forces the opponent into a LOSING state. A state is LOSING if ALL moves lead to winning states for the opponent. This recursive definition is exactly what DP captures.
Tip
⚡ Optimization Tip: We can compute the current sum from the mask by precomputing a sumMap[mask]array. But for n ≤ 20, the extra O(n) per state is fine (20M operations).
Also note: we don't need to track whose turn it is in the DP state — the mask tells us! The number of set bits = number of moves made. Even = P2's turn, Odd = P1's turn.
PROBLEMCan I Win
Two players take turns picking numbers 1 to n. Can the first player force a win to reach the target sum?
Editable example loads when this section enters view.
5. Fair Distribution of Cookies — Minimize the Maximum Load
Problem: You have k children and n bags of cookies. Each bag has a certain number of cookies. You must give each bagto exactly one child. Your goal: minimize the maximum number of cookiesany child gets.
Note
🍪 Real-World Analogy: Imagine you're a parent with k children and n bags of cookies. Each bag has a different number of cookies. You need to give every bag to exactly one child. You want to minimize jealousy — the maximum number of cookies any single child gets. This is a "min-max" optimization: assign bags to children such that the child with the most cookies gets as few as possible.
🤔 Think About It
This is a min-max optimization problem. We want to distribute cookies so the child with the most cookies gets as few as possible. It's NP-hard — for small n, we can use bitmask DP.
The DP Approach
Instead of assigning bags one by one (which is hard), we think about it differently: which subset of bags goes to each child?
For each subset (bitmask), we precompute its total sum. Then we distribute masks to k children, minimizing the max sum.
example.js
function distributeCookies(cookies, k) {
const n = cookies.length;
const totalMasks = 1 << n;
// Precompute sum of every subset
const sum = new Array(totalMasks).fill(0);
for (let mask = 0; mask < totalMasks; mask++) {
for (let i = 0; i < n; i++) {
if (mask & (1 << i)) {
sum[mask] += cookies[i];
}
}
}
// dp[child][mask] = min max load when 'child' children
// have been assigned, using subset 'mask'
const dp = Array.from({ length: k + 1 }, () =>
new Array(totalMasks).fill(Infinity)
);
dp[0][0] = 0; // 0 children, 0 cookies → max = 0
for (let child = 1; child <= k; child++) {
for (let mask = 0; mask < totalMasks; mask++) {
// Try all subsets of the remaining masks
let submask = mask;
while (submask) {
const prevMask = mask ^ submask;
const maxLoad = Math.max(
dp[child - 1][prevMask],
sum[submask]
);
dp[child][mask] = Math.min(dp[child][mask], maxLoad);
submask = (submask - 1) & mask;
}
}
}
return dp[k][totalMasks - 1];
}
// OPTIMIZED: Single-dimension DP
function distributeCookiesOptimized(cookies, k) {
const n = cookies.length;
const totalMasks = 1 << n;
// Precompute subset sums
const sum = new Array(totalMasks).fill(0);
for (let mask = 0; mask < totalMasks; mask++) {
for (let i = 0; i < n; i++) {
if (mask & (1 << i)) sum[mask] += cookies[i];
}
}
// dp[mask] = min possible max load with current child assignment
let dp = new Array(totalMasks).fill(Infinity);
dp[0] = 0;
for (let child = 1; child <= k; child++) {
const next = new Array(totalMasks).fill(Infinity);
for (let mask = 0; mask < totalMasks; mask++) {
// Iterate submasks of the COMPLEMENT of mask
const remaining = (totalMasks - 1) ^ mask;
let submask = remaining;
while (submask) {
const newMask = mask | submask;
const maxLoad = Math.max(dp[mask], sum[submask]);
next[newMask] = Math.min(next[newMask], maxLoad);
submask = (submask - 1) & remaining;
}
}
dp = next;
}
return dp[totalMasks - 1];
📊 Visualization
For cookies = [6, 1, 3, 2, 1, 7, 4] and k = 3:
Child
Assigned Bags (indices)
Sum
A
5 (7), 2 (3)
10
B
0 (6), 3 (2), 4 (1)
9
C
6 (4), 1 (1)
5
Max
10 (minimum possible)
Key Insight
🔑 The Key Pattern: The "subset enumeration over complement" trick submask = (submask - 1) & remaining is the efficient way to iterate all subsets of the remaining (unassigned) elements. This gives us O(k × 3ⁿ) complexity — better than the naive O(k × 4ⁿ).
PROBLEMFair Distribution of Cookies
Distribute cookie bags to k children to minimize the maximum number of cookies any child receives. Bitmask DP with subset enumeration.
Editable example loads when this section enters view.
6. Common Bitmask DP Patterns — Beyond the Basics
Once you understand the core pattern, you can apply it to MANY problems. Here are the most common variations:
Hamiltonian Path — dp[mask][last]
Find a path that visits every vertex exactly once. The state isdp[mask][last] where mask tells us which vertices are visited and last is the current vertex.
example.js
// Hamiltonian Path existence
function hamiltonianPath(graph) {
const n = graph.length;
const totalMasks = 1 << n;
// dp[mask][last] = can we reach this state?
const dp = Array.from({ length: totalMasks }, () => new Array(n).fill(false));
// Base: single vertex paths
for (let i = 0; i < n; i++) dp[1 << i][i] = true;
for (let mask = 0; mask < totalMasks; mask++) {
for (let last = 0; last < n; last++) {
if (!dp[mask][last]) continue;
// Try extending to an unvisited neighbor
for (let next = 0; next < n; next++) {
if ((mask & (1 << next)) === 0 && graph[last][next]) {
dp[mask | (1 << next)][next] = true;
}
}
}
}
// Check if any full-path state is reachable
for (let last = 0; last < n; last++) {
if (dp[totalMasks - 1][last]) return true;
}
return false;
Traveling Salesman (TSP) — Minimize Path Cost
Same as Hamiltonian, but we want the minimum costpath. Instead of boolean, dp stores the minimum distance.
example.js
function tsp(dist) {
const n = dist.length;
const totalMasks = 1 << n;
const dp = Array.from({ length: totalMasks }, () => new Array(n).fill(Infinity));
// Start from city 0
dp[1][0] = 0;
for (let mask = 0; mask < totalMasks; mask++) {
for (let last = 0; last < n; last++) {
if (dp[mask][last] === Infinity) continue;
for (let next = 0; next < n; next++) {
if ((mask & (1 << next)) === 0) {
const newMask = mask | (1 << next);
dp[newMask][next] = Math.min(
dp[newMask][next],
dp[mask][last] + dist[last][next]
);
}
}
}
}
// Return to city 0
let minCost = Infinity;
for (let last = 1; last < n; last++) {
minCost = Math.min(minCost, dp[totalMasks - 1][last] + dist[last][0]);
}
return minCost;
Vertex Cover — Minimum Set of Vertices
Find the smallest set of vertices such that every edge touches at least one vertex in the set.
example.js
function minVertexCover(edges, n) {
// edges = [[u,v], ...]
const totalMasks = 1 << n;
let minSize = n;
for (let mask = 0; mask < totalMasks; mask++) {
let covered = true;
for (const [u, v] of edges) {
if (!(mask & (1 << u)) && !(mask & (1 << v))) {
covered = false;
break;
}
}
if (covered) {
minSize = Math.min(minSize, popcount(mask));
}
}
return minSize;
function popcount(x) {
let c = 0;
while (x) { c += x & 1; x >>>= 1; }
return c;
}
Pattern Summary
Pattern
State
Recurrence
Complexity
Subset Sum
dp[mask]
dp[mask|1<<i] = dp[mask] + val[i]
O(n × 2ⁿ)
Hamiltonian
dp[mask][last]
dp[mask|1<<i][i] = true
O(n² × 2ⁿ)
TSP
dp[mask][last]
min(dp[mask][last] + dist[last][i])
O(n² × 2ⁿ)
Game Theory
dp[mask]
!dp[mask|1<<i] → win
O(n × 2ⁿ)
Partition
dp[mask]
dp[mask] = sum[mask] if reachable
O(n × 2ⁿ)
Min-Max
dp[child][mask]
min(max(dp[c-1][p], sum[m-p]))
O(k × 3ⁿ)
Note
🧠 Pro Tip: The biggest optimization in Bitmask DP issubset enumeration over a mask's complement. Thesubmask = (submask - 1) & remaining loop iterates over all subsets of remaining in O(3ⁿ) instead of O(4ⁿ). This is critical for min-max problems like Fair Cookies.
🎯 Interview Cheat Sheet
Key Insight
Q1: When should I use Bitmask DP vs backtracking? Bitmask DP when: n ≤ 20, you need optimal solution, there's a clear state transition. Backtracking when: you need just one valid solution, pruning rules are obvious, n ≤ 15.
Key Insight
Q2: How do I know if bitmask DP applies? Look for keywords: "subset", "partition", "each element used once", "minimize maximum", "game with take turns", "visit all nodes". If the state can be described as "which items are selected", bitmask DP works.
Key Insight
Q3: Can I optimize the mask iteration? YES! Instead of iterating all masks and checking if element is unused, precompute unused[mask] or use Gosper's Hackto iterate only valid masks. For subset enumeration, thesubmask = (submask - 1) & mask trick is essential.
Key Insight
Q4: What about memory? dp array of size 2ⁿ with integers is ~8 MB for n=20. For n=22, it's ~32 MB. For 2D dp (TSP), dp[2ⁿ][n] is ~160 MB for n=20 — might be too much. Use typed arrays (Int32Array) or prune states.
Key Insight
Q5: What about the "beautiful arrangement" problem? This is a counting problem: count permutations where each number is divisible by its position OR position is divisible by the number. dp[mask] = number of ways to arrange the selected elements. At step = popcount(mask), try placing any unused number that satisfies the condition at position step+1.
Key Insight
Q6: How is Beautiful Arrangement different from Partition? Beautiful Arrangement is a counting problem (how many ways), not a decision problem (can we do it). The state is still dp[mask], but we sum dp[mask] + dp[newMask] instead of taking max/min. This is because we're counting arrangements, not optimizing.
📝 Key Takeaways
Bitmask DP = DP over subsets — encode "which elements are selected" as bits in an integer
n ≤ 20 is the sweet spot — 2ⁿ states, O(n × 2ⁿ) operations, ~20M for n=20
Recurrence pattern: for each mask, try adding each unused element: mask | (1 << i)
Sort descending + pruning — for partition problems, large-first ordering and empty-bucket prune are game-changing
Game theory: dp[mask] = can current player win? True if ANY move reaches target OR forces opponent loss
Min-max optimization: iterate submasks of complement using (submask - 1) & remaining
Hamiltonian Path / TSP: add a dimension for "last visited" vertex — dp[mask][last]
Precompute subset sums — cache sum[mask] to avoid O(n) recomputation per state
Counting vs Optimization: counting sums dp values, optimization takes max/min
Practice! — Bitmask DP is a superpower. Once you've seen the patterns, you'll spot them everywhere 🎯
Note
🔮 Practice Problems to Solve: Partition to K Equal Sum Subsets, Matchsticks to Square, Can I Win, Beautiful Arrangement, Fair Distribution of Cookies, Total Appeal of All Paths, Hamiltonian Path, TSP