Skip to lesson

Bitmask dynamic programming

Bitmask dynamic programming represents subsets of elements as binary bits within a single integer. When n <= 20, bitmasks turn exponential brute force searches into structured polynomial-time transitions.

Brute Force Permutations and the TSP Problem

The Traveling Salesperson Problem (TSP) asks for the cheapest route that visits all n cities and returns to the origin. Without dynamic programming, plain recursion tries every unvisited city as the next stop (shown after the code).

Java
int tour(int[][] dist, boolean[] visited, int city, int count) {    if (count == dist.length) return dist[city][0]; // all visited: go home    int best = Integer.MAX_VALUE;    for (int next = 0; next < dist.length; next++) {        if (visited[next]) continue;        visited[next] = true;        best = Math.min(best, dist[city][next] + tour(dist, visited, next, count + 1));        visited[next] = false;                       // undo for the next route    }    return best;}

With plain recursion, we explore every possible permutation of visiting cities. For n cities, there are (n - 1)! possible routes. For n = 15 cities, 14! is over 87 billion routes, which takes hours to run!

Why is plain recursion wasteful? Suppose two different routes both visit cities {1, 3, 4} and currently end at city 4. To finish the tour, both routes face the exact same remaining unvisited cities! Storing the optimal cost for state (visited_subset, current_city) collapses billions of redundant paths into a compact table.

Representing Subsets with Bitwise Arithmetic

A bitmask stores a subset of n items as one integer from 0 to (1 << n) - 1. The i-th bit is 1 if item i is in the subset, and 0 if item i is absent.

BitmaskOps.javaJava
public class BitmaskOps {    public static void main(String[] args) {        int mask = 0b1011;                  // items {0, 1, 3}        System.out.println("has 1? " + (((mask >> 1) & 1) == 1));        System.out.println("has 2? " + (((mask >> 2) & 1) == 1));        mask = mask | (1 << 2);             // add item 2        System.out.println("after add 2: " + Integer.toBinaryString(mask));        mask = mask & ~(1 << 0);            // remove item 0        System.out.println("after remove 0: " + Integer.toBinaryString(mask));    }}
Output
has 1? true
has 2? false
after add 2: 1111
after remove 0: 1110

Three core bitwise operations manage subset states:

  • Query membership: ((mask >> i) & 1) == 1
  • Add element i: mask | (1 << i)
  • Remove element i: mask & ~(1 << i)

Because bitwise operations operate directly on CPU registers, querying and updating subset states takes constant O(1) time.

Predict the output

Predict the bit operation

Work out each result in binary, then pick what is printed.

Round 1 of 3

int mask = 10; // binary 1010
mask = mask | (1 << 0);
System.out.println(mask);

The Traveling Salesperson State Transitions

Define dp[mask][u] as the minimum travel distance starting at city 0, having visited the subset of cities in mask, and currently standing at city u.

Example 1 · TSP by trying every route, brute force: O(n!) time, O(n) space

TspBruteDemo.javaJava
public class TspBruteDemo {    static int best = Integer.MAX_VALUE;
    static void route(int[][] dist, boolean[] visited, int city, int count, int cost) {        if (count == dist.length) {                       // every city visited            best = Math.min(best, cost + dist[city][0]);  // add the trip home            return;        }        for (int next = 1; next < dist.length; next++) {            if (!visited[next]) {                visited[next] = true;                route(dist, visited, next, count + 1, cost + dist[city][next]);                visited[next] = false;                    // undo, try another order            }        }    }
    public static void main(String[] args) {        int[][] dist = {            {0, 10, 15, 20},            {10, 0, 35, 25},            {15, 35, 0, 30},            {20, 25, 30, 0}        };        boolean[] visited = new boolean[dist.length];        visited[0] = true;        route(dist, visited, 0, 1, 0);        System.out.println("Shortest TSP tour: " + best);    }}
Output
Shortest TSP tour: 80

What this code does

  • Fixes city 0 as the start and tries every order of the other cities: (n - 1)! routes.
  • visited[] marks cities on the current route; setting it back to false lets the next order reuse the city.
  • It prints 80, the same answer as the bitmask version, but the work grows factorially.

Example 2 · TSP with bitmask DP, optimal: O(n² · 2^n) time, O(n · 2^n) space

TSPDemo.javaJava
import java.util.Arrays;
public class TSPDemo {    public static int tsp(int[][] dist) {        int n = dist.length;        int totalStates = 1 << n;        int[][] dp = new int[totalStates][n];        for (int[] row : dp) Arrays.fill(row, 1_000_000_000);
        // Start at city 0        dp[1][0] = 0;
        for (int mask = 1; mask < totalStates; mask++) {            for (int u = 0; u < n; u++) {                if ((mask & (1 << u)) == 0 || dp[mask][u] >= 1_000_000_000) continue;                for (int v = 0; v < n; v++) {                    if ((mask & (1 << v)) == 0) {                        int nextMask = mask | (1 << v);                        dp[nextMask][v] = Math.min(dp[nextMask][v], dp[mask][u] + dist[u][v]);                    }                }            }        }
        int minCost = Integer.MAX_VALUE;        int fullMask = (1 << n) - 1;        for (int u = 1; u < n; u++) {            minCost = Math.min(minCost, dp[fullMask][u] + dist[u][0]);        }        return minCost;    }
    public static void main(String[] args) {        int[][] dist = {            {0, 10, 15, 20},            {10, 0, 35, 25},            {15, 35, 0, 30},            {20, 25, 30, 0}        };        System.out.println("Shortest TSP tour: " + tsp(dist));    }}
Output
Shortest TSP tour: 80

What this code does

  • Defines dp[mask][u] storing minimum distance visiting subset mask and ending at city u.
  • Transitions to unvisited city v by setting bit v using bitwise OR (mask | (1 << v)).
  • Completes the tour by adding return edge dist[u][0] from final city u back to origin 0.
  • Why faster: routes that visit the same set of cities and end in the same city are solved once, so (n - 1)! routes shrink to about 2^n · n states.

From city u, we try moving to any unvisited city v (where (mask & (1 << v)) == 0). The transition evaluates dp[mask | (1 << v)][v] = Math.min(dp[mask | (1 << v)][v], dp[mask][u] + dist[u][v]). There are 2^n masks and n ending cities, giving n * 2^n states. Each state checks at most n next cities, solving TSP in O(n^2 * 2^n) time instead of O(n!) factorial brute force.

Optimal Assignment and Submask Enumeration

In task assignment, dp[mask] stores the minimum cost to assign tasks represented by mask to the first k workers, where k = Integer.bitCount(mask).

Example 3 · Worker assignment by trying every pairing, brute force: O(n!) time, O(n) space

AssignBruteDemo.javaJava
public class AssignBruteDemo {    static int best = Integer.MAX_VALUE;
    static void assign(int[][] cost, int worker, boolean[] taken, int total) {        if (worker == cost.length) {            best = Math.min(best, total);            return;        }        for (int task = 0; task < cost.length; task++) {            if (!taken[task]) {                taken[task] = true;                assign(cost, worker + 1, taken, total + cost[worker][task]);                taken[task] = false;            }        }    }
    public static void main(String[] args) {        int[][] cost = {            {9, 2, 7},            {6, 4, 3},            {5, 8, 1}        };        assign(cost, 0, new boolean[cost.length], 0);        System.out.println("Minimum assignment cost: " + best);    }}
Output
Minimum assignment cost: 9

What this code does

  • Worker 0 tries each free task, then worker 1 tries each task still free, and so on.
  • taken[] marks the tasks already used on the current path and is reset after each try.
  • For 3 workers there are 3! = 6 pairings; for 20 workers there would be over 2 quintillion.

Example 4 · Worker assignment with bitmask DP, optimal: O(n · 2^n) time, O(2^n) space

AssignmentDemo.javaJava
import java.util.Arrays;
public class AssignmentDemo {    public static int minCost(int[][] cost) {        int n = cost.length;        int[] dp = new int[1 << n];        Arrays.fill(dp, 1_000_000_000);        dp[0] = 0;
        for (int mask = 0; mask < (1 << n); mask++) {            int worker = Integer.bitCount(mask);            if (worker >= n) continue;            for (int task = 0; task < n; task++) {                if ((mask & (1 << task)) == 0) {                    int nextMask = mask | (1 << task);                    dp[nextMask] = Math.min(dp[nextMask], dp[mask] + cost[worker][task]);                }            }        }        return dp[(1 << n) - 1];    }
    public static void main(String[] args) {        int[][] cost = {            {9, 2, 7},            {6, 4, 3},            {5, 8, 1}        };        System.out.println("Minimum assignment cost: " + minCost(cost));    }}
Output
Minimum assignment cost: 9

What this code does

  • Represents the set of already assigned tasks as a bitmask of size 2^n.
  • Derives the next worker index automatically from Integer.bitCount(mask).
  • Finds the global optimum cost 9 by matching worker 0 to task 1 (cost 2), worker 1 to task 0 (cost 6), and worker 2 to task 2 (cost 1).
  • Why faster: dp[mask] remembers the best cost for each set of used tasks, so the n! pairings share their partial results.

Example 5 · Submask enumeration: O(2^k) steps for k set bits

SubmaskDemo.javaJava
public class SubmaskDemo {    public static int countSubmasks(int mask) {        int count = 0;        for (int sub = mask; sub > 0; sub = (sub - 1) & mask) {            count++;        }        return count + 1; // including empty submask 0    }
    public static void main(String[] args) {        int mask = 13; // binary 1101 (3 bits set)        System.out.println("Submasks of 13 count: " + countSubmasks(mask));    }}
Output
Submasks of 13 count: 8

What this code does

  • A mask with k set bits has exactly 2^k submasks.
  • The bitwise trick (sub - 1) & mask steps directly to the next lower submask in O(1) time.
  • Mask 13 has 3 set bits (bits 0, 2, 3), yielding 2^3 = 8 submasks.

When problems require partitioning subsets into smaller sub-subsets, the bitwise idiom for (int sub = mask; sub > 0; sub = (sub - 1) & mask) visits every non-empty submask of mask in decreasing order. Across all masks of size n, summing all submasks takes O(3^n) total steps, unlocking optimal subset grouping algorithms.

Next step

Check your understanding

10 quick questions