Bitmask DP
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Bitmask DP uses a single number whose binary digits act as on/off switches to record which items from a small set have been used. The table stores the best result for each pattern of switches. It handles problems with up to about 20 items where order or assignment matters.
Practical use cases
- Web app: Assigning delivery riders to orders. A food-delivery dispatcher has 5 riders and 5 orders, with a different travel time for each pair, and wants the lowest total time. Each pattern of already-assigned orders is stored as a small number with the best time so far. The assignment is found in a blink, instead of trying all 120 pairings.
- Web app: Planning a short multi-stop trip. A trip-planner app lets a user choose up to 12 places to visit and returns the shortest tour. It remembers the best cost for every set of visited places and current location. That is far faster than trying every order.
- System: Travelling salesman and puzzle solvers. The travelling salesman problem for small sets uses exactly this method, and many puzzle solvers use switch-patterns to remember which pieces are placed.
The story: The Light Switches of Chai Corner
Raju had three helpers and three jobs at the chai stall: boil the milk, wash the cups, take orders. Each helper was faster at some jobs than others, so each pairing had a cost. Everyone must do exactly one job. Which assignment gives the lowest total cost? With three jobs you can try all 6 arrangements by hand; but with 15 helpers there are over a trillion.
Mira noticed that what really matters at any moment is which jobs are already taken, not who took which. She hung three light switches on the wall, one per job. A pattern like 101 means job 1 and job 3 are taken. With n jobs there are only 2ⁿ patterns, far fewer than all arrangements. She wrote on a board the cheapest cost to reach each switch pattern.
Helpers are handled in order: if two switches are on, the third helper picks next. From each pattern, try each job still off, switch it on, and keep the cheaper cost. After going through all patterns, the "all on" pattern held 9. This trick, packing a set into one small number of on/off bits, is Bitmask DP. Honest note: three jobs is the smallest example that still shows the idea. Its true power starts at about 15 to 20 items.
How to spot this problem, and where you need it
You must choose or order items from a small set and the best next step depends on exactly which items are already used.
Signs you need it
- The input is small, roughly 20 items or fewer, and the problem says "visit all", "assign each exactly once" or "cover every item".
- A table indexed by simple numbers is not enough because you must remember a whole set of used items.
- Brute-forcing every order is too slow beyond about 10 items.
Where to use it in a project
- Planning short tours or multi-stop routes in travel, delivery or field-service apps.
- Assigning a small number of workers, rooms or vehicles to tasks at the lowest total cost.
The solution
Represent each set of used items as a binary number: bit i is 1 if item i is used. Make a table indexed by that number holding the best cost for that set. Start with the empty set at cost 0. For each set, try adding each unused item, flip its bit, and update the cost of the new set if better. The cost of the full set, all bits on, is the answer.
Payoff: Before: about 479 million orders to try for 12 stops. After: about 50,000 table entries, ready in a fraction of a second.
Explain it like I am 8
Imagine a row of light switches, one for each job. A switch is on when the job is taken. Every pattern of switches is just one number, like a secret code. You keep a notebook with the cheapest cost to reach each code, and only ever flip off-switches on.
How it works, step by step
- Name each item by a switch: job
jis bitj. The set of taken jobs is one integermask. dp[mask]= cheapest cost with those jobs taken.dp[0] = 0; the rest start as "unreachable".- How many helpers are done = how many bits are on, so the next helper is
popcount(mask). - For each job
jnot inmask:dp[mask | (1 << j)] = min(that, dp[mask] + cost[helper][j]). - Go through masks in increasing order. The answer is
dp[all bits on].
The code in four languages
PHP
<?php
// cost[w][j]: price for helper w to do job j. Each helper gets exactly one job.
function minAssignment(array $cost): int {
$n = count($cost);
$full = 1 << $n; // 2^n switch patterns
$dp = array_fill(0, $full, PHP_INT_MAX);
$dp[0] = 0; // nothing taken, nothing paid
for ($mask = 0; $mask < $full - 1; $mask++) {
if ($dp[$mask] === PHP_INT_MAX) continue;
$w = 0; // helper = number of switches already on
for ($m = $mask; $m > 0; $m >>= 1) $w += $m & 1;
for ($j = 0; $j < $n; $j++) {
if ($mask & (1 << $j)) continue; // job j already taken
$next = $mask | (1 << $j); // flip switch j on
$dp[$next] = min($dp[$next], $dp[$mask] + $cost[$w][$j]);
}
}
return $dp[$full - 1];
}
echo minAssignment([[9, 2, 7], [6, 4, 3], [5, 8, 1]]), "\n"; // 9JavaScript
// cost[w][j]: price for helper w to do job j. Each helper gets exactly one job.
function minAssignment(cost) {
const n = cost.length;
const full = 1 << n; // 2^n switch patterns
const dp = new Array(full).fill(Infinity);
dp[0] = 0; // nothing taken, nothing paid
for (let mask = 0; mask < full - 1; mask++) {
if (dp[mask] === Infinity) continue;
let w = 0; // helper = number of switches already on
for (let m = mask; m > 0; m >>= 1) w += m & 1;
for (let j = 0; j < n; j++) {
if (mask & (1 << j)) continue; // job j already taken
const next = mask | (1 << j); // flip switch j on
dp[next] = Math.min(dp[next], dp[mask] + cost[w][j]);
}
}
return dp[full - 1];
}
console.log(minAssignment([[9, 2, 7], [6, 4, 3], [5, 8, 1]])); // 9Java
import java.util.*;
public class Main {
// cost[w][j]: price for helper w to do job j. Each helper gets exactly one job.
static int minAssignment(int[][] cost) {
int n = cost.length;
int full = 1 << n; // 2^n switch patterns
int[] dp = new int[full];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0; // nothing taken, nothing paid
for (int mask = 0; mask < full - 1; mask++) {
if (dp[mask] == Integer.MAX_VALUE) continue;
int w = Integer.bitCount(mask); // helper = number of switches already on
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) != 0) continue; // job j already taken
int next = mask | (1 << j); // flip switch j on
dp[next] = Math.min(dp[next], dp[mask] + cost[w][j]);
}
}
return dp[full - 1];
}
public static void main(String[] args) {
int[][] cost = {{9, 2, 7}, {6, 4, 3}, {5, 8, 1}};
System.out.println(minAssignment(cost)); // 9
}
}Go
package main
import (
"fmt"
"math"
"math/bits"
)
// minAssignment: cost[w][j] is the price for helper w to do job j.
// Each helper gets exactly one job.
func minAssignment(cost [][]int) int {
n := len(cost)
full := 1 << n // 2^n switch patterns
dp := make([]int, full)
for i := range dp {
dp[i] = math.MaxInt
}
dp[0] = 0 // nothing taken, nothing paid
for mask := 0; mask < full-1; mask++ {
if dp[mask] == math.MaxInt {
continue
}
w := bits.OnesCount(uint(mask)) // helper = number of switches already on
for j := 0; j < n; j++ {
if mask&(1<<j) != 0 { // job j already taken
continue
}
next := mask | (1 << j) // flip switch j on
dp[next] = min(dp[next], dp[mask]+cost[w][j])
}
}
return dp[full-1]
}
func main() {
cost := [][]int{{9, 2, 7}, {6, 4, 3}, {5, 8, 1}}
fmt.Println(minAssignment(cost)) // 9
}Time: O(2ⁿ × n) · Extra space: O(2ⁿ). Far better than trying all n! orderings, but still exponential: use it for n up to roughly 20.
Watch out for
- Using it for huge n. 2ⁿ patterns blow up quickly; bitmask DP is for small sets only.
- Forgetting operator precedence: write
(mask & (1 << j))with brackets. - Processing masks out of order. A mask must be final before it feeds the bigger ones; going upwards 0, 1, 2... guarantees that.
Quick check
- What does the number "101" (as switches) mean here?
- Job 1 and job 3 are taken
- Cost is 101
- Only job 2 is taken
- How many switch patterns for 3 jobs?
- 6
- 8
- 3
- How do we know which helper is next?
- We store it separately
- The number of switches already on
- Always the first helper