Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Dynamic Programming

Sets as Integers.

Some problems have a state that is a set — “which cities have I visited?” The trick that makes them tractable is representing that set as the bits of an integer: with n items, a subset is a number from 0 to 2ⁿ−1, and set operations become fast bitwise ops. Bitmask DP then dynamic-programs over states like (subset, current position). On the traveling salesman problem this is the Held–Karp algorithm: O(2ⁿ·n²) instead of the brute-force O(n!) — still exponential, but astronomically smaller for real n. Step through the subsets and watch the optimal tour assemble.

TSP in O(2ⁿ·n²) vs O(n!) · a subset = the bits of an integer · state = (visited-set, position)
bitmask

An integer whose bit i means “item i is in the set.” 0b01011 = {0,1,3}.

state

Here (mask, last): the set of visited cities, and which one we’re standing on.

transition

From (mask, last), go to an unvisited city j: (mask | 1<<j, j).

Held–Karp

The bitmask-DP solution to TSP: O(2ⁿ·n²) time, O(2ⁿ·n) space.

held-karp.js — a subset is a number
Ready
Five cities; find the shortest tour from city 0 back to city 0. The DP state is (visited-set, last city), and the visited-set is stored as a 5-bit mask. We fill subsets from small to large. Step through them.
00001
current mask
0
states filled
–
best tour

How it works

The brute-force TSP tries all (n−1)! orderings — hopeless past a dozen cities. Held–Karp’s insight is that two partial tours visiting the same set of cities and ending at the same city are interchangeable going forward: only the cheapest one can matter. So define dp[mask][i] = the cheapest way to start at city 0, visit exactly the cities in mask, and end at city i. Fill masks from smallest to largest; each state extends by adding one unvisited city. There are 2ⁿ·n states and each looks at n transitions, giving O(2ⁿ·n²). For n = 15 that’s about 7 million operations versus 15! ≈ 1.3 trillion — the difference between instant and never.

1

Encode the visited set as bits

With n cities, the set of visited ones is an n-bit integer: bit i set means city i is visited. Adding a city is mask | (1<<city); testing is mask & (1<<city).

2

Define the state

dp[mask][i] = minimum cost to start at city 0, visit exactly the cities in mask, and currently be at city i. Base case: dp[{0}][0] = 0.

3

Fill masks small to large

For each state (mask, i), try going to each unvisited city j: dp[mask | 1<<j][j] = min(…, dp[mask][i] + dist(i, j)). Because you only add bits, larger masks depend only on smaller ones.

✓

Close the tour

Once the full mask (all cities) is reached, add the edge back to city 0: answer = min over i of dp[full][i] + dist(i, 0). Reconstruct the path via stored choices.

TSP time
O(2ⁿ·n²)
vs brute force
O(n!)
States
2ⁿ · n
Set ops
bitwise

The code

# Held-Karp: exact TSP via bitmask DP, O(2^n * n^2) dp = [[inf]*n for _ in range(1<<n)] dp[1][0] = 0 # start at city 0, mask = {0} for mask in range(1<<n): for i in range(n): if dp[mask][i] == inf: continue for j in range(n): if mask & (1<<j): continue # j already visited nm = mask | (1<<j) # add city j to the set dp[nm][j] = min(dp[nm][j], dp[mask][i] + dist[i][j]) ans = min(dp[(1<<n)-1][i] + dist[i][0] for i in range(1, n))

Quick check

1. How is a subset of n items represented in bitmask DP?

2. In Held–Karp, what is the DP state?

3. How does Held–Karp compare to brute-force TSP?

FAQ

What is bitmask DP?

Dynamic programming where part of the state is a subset, encoded as the bits of an integer — making set membership, union, and iteration fast via bitwise ops, and letting you index a DP table by subset. It’s standard for problems with up to ~20 items whose state includes “which items are used.”

What is the Held–Karp algorithm?

The bitmask-DP solution to the traveling salesman problem: dp[mask][i] is the cheapest route starting at a fixed city, visiting exactly the cities in mask, ending at i, filled small-to-large. O(2ⁿ·n²) time, O(2ⁿ·n) space — the best known exact TSP algorithm, far faster than all n! tours.

What is the practical limit on bitmask DP?

The 2ⁿ factor makes it practical to about n = 20 (2²⁰ ≈ a million subsets, times n or n²). Beyond that it’s too large. For bigger TSP you switch to heuristics — nearest neighbor, 2-opt, simulated annealing — giving good but not provably optimal tours.

What other problems use bitmask DP?

Assignment problems (match n workers to n tasks), counting Hamiltonian paths, shortest superstring, broken-profile/plug DP on grids, subset-sum and partition variants, and many “use every item once” problems — whenever the state must remember an arbitrary subset of a small universe.

The picture: subsets in layers

1 visited 2 visited 3 visited 4 visited 0001 start: 0 0011 1:10 0101 2:15 1001 3:20 0111 1:50 2:45 1011 1:45 3:35 1101 2:50 3:45 1111 1:70 2:65 3:75 close the tour: 70+10 = 65+15 = 80; 75+20 = 95
The 4-city matrix from the page’s first test, with city 0 as the start. Each box is a visited set containing city 0; the pairs show last:cost, the cheapest way to have visited exactly that set and be standing on that city. Edges add one city. The highlighted chain 0001, 0101, 1101, 1111 is the optimal tour 0, 2, 3, 1 and back, costing 80.

Worked example, step by step

The distance matrix is [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] and the tour starts and ends at city 0. The base state is dp[0001][0] = 0. Masks are written with bit 0 on the right, so 0101 means cities {0, 2}. Each row below is a state reached by adding city Last to the set before it.

MaskSetLastHow it is reacheddp
0011{0,1}1dp[0001][0] + d(0,1) = 0 + 1010
0101{0,2}2dp[0001][0] + d(0,2) = 0 + 1515
1001{0,3}3dp[0001][0] + d(0,3) = 0 + 2020
0111{0,1,2}1dp[0101][2] + d(2,1) = 15 + 3550
0111{0,1,2}2dp[0011][1] + d(1,2) = 10 + 3545
1011{0,1,3}1dp[1001][3] + d(3,1) = 20 + 2545
1011{0,1,3}3dp[0011][1] + d(1,3) = 10 + 2535
1101{0,2,3}2dp[1001][3] + d(3,2) = 20 + 3050
1101{0,2,3}3dp[0101][2] + d(2,3) = 15 + 3045
1111{0,1,2,3}1min(50+35, 45+25) = min(85, 70)70
1111{0,1,2,3}2min(45+35, 35+30) = min(80, 65)65
1111{0,1,2,3}3min(50+25, 45+30) = min(75, 75)75

There are 12 reachable states beyond the base. Look at row 10 (mask 1111, last city 1): two predecessors compete, 85 and 70, and the 85 is thrown away. That is the whole algorithm: of all the orders that visit the same set and end at the same city, only the cheapest survives. To finish, add the edge home: 70 + d(1,0) = 80, 65 + d(2,0) = 80 and 75 + d(3,0) = 95, so the answer is 80. Following the winning predecessors backwards from state (1111, 1) gives 0 → 2 → 3 → 1 → 0 (cost 15 + 30 + 25 + 10); the other tie, ending at city 2, is the same tour run in reverse. A brute-force check over all 6 orderings also returns 80. At n = 4 the DP does 15 transitions against 6 orderings, so it is not yet a saving; the savings arrive as n grows.

Complexity and trade-offs

CaseTimeSpaceWhy
Held–KarpO(2ⁿ·n²)O(2ⁿ·n)Counted transitions on random matrices: 9,225 for n = 10 and 56,331 for n = 12.
Brute force over ordersO(n!)O(n)(n−1)! tours: 362,880 at n = 10, 39,916,800 at n = 12, 121,645,100,408,832,000 at n = 20.
Held–Karp, two layers keptO(2ⁿ·n²)at most C(n, n/2)·nFor n = 20 that is 3,695,120 states per layer instead of 20,971,520 in total. Recovering the tour then needs extra bookkeeping.
Nearest neighbour heuristicO(n²)O(n)Not exact. On a 9-city symmetric matrix (weights 1–99, Random(1)) it returns 181; the true optimum is 111.

Held–Karp turns a factorial into an exponential, which is a different league but still not a polynomial: each added city doubles the table. The table size is the real limit. With 8-byte entries, n = 20 needs 20,971,520 of them (about 168 MB), and n = 25 needs 838,860,800. Time and memory therefore run out together somewhere in the low twenties. Beyond that, exact methods need pruning (branch and bound) and good answers need heuristics, as the nearest-neighbour row shows: fast, but 63% above optimal on that instance.

Common mistakes

  • Operator precedence in the membership test

    In JavaScript and C, == binds tighter than &. With mask = 5 and j = 1, mask & 1<<j == 0 evaluates to 0 (false) even though city 1 is not in the set, and it is 0 for every j. Write (mask & (1<<j)) == 0, which is true here.

  • Infinity that overflows

    In a 32-bit integer table, a sentinel of 2147483647 plus an edge of 10 wraps to −2147483639, which looks like the cheapest cost ever seen. Either skip states that are still infinite (as the page’s code does) or use a sentinel such as half the maximum.

  • Letting the tour start anywhere

    Initialising dp[1<<i][i] = 0 for every i, then closing back to city 0, mixes up the start. On the 4-city matrix it returns 65, which is cheaper than any real tour (the optimum is 80). Only dp[1][0] = 0 is a valid base.

  • Forgetting the edge home

    min(dp[full][i]) without adding d(i, 0) is the cheapest Hamiltonian path, not the tour. Here that gives 65 instead of 80. Always add the closing edge before taking the minimum.

  • Allocating the table for a large n

    dp = [[inf] * n for _ in range(1 << n)] at n = 25 asks for 838,860,800 entries. The program fails on memory before time becomes the problem. Check 2ⁿ·n against the memory you have, not just the loop count.

Where this shows up

  • Assignment with a small side

    Assigning n workers to n jobs where each job is used once: the state is the set of jobs already taken, with the worker index implied by the popcount. For n = 12 that is 4,096 masks instead of 479,001,600 permutations.

  • Counting Hamiltonian paths and cycles

    The same (mask, last) state with a sum instead of a min counts the paths. It is the standard exact approach when n is around 20 or less.

  • Shortest common superstring

    Treat each string as a city and the overlap as the edge weight; the tour or path problem is the same DP.

  • Contest and interview problems with a tiny universe

    Any statement with “each item used at most once” and a limit of about 20 items is a hint. Typical cases are covering a set with the fewest tiles, scheduling tasks with deadlines, and partitioning a group into teams.

SOLVE IT YOURSELF

Solve it: the travelling salesman, exactly

Every tour of n cities is n! permutations — 3.6 million at n = 10. But there are only 2ⁿ sets of visited cities, and the route there stops mattering once you know where you are. That collapses it to 2ⁿ·n². Python or TypeScript.

YOUR TASK

Implement tsp(dist): given a full distance matrix, return the cost of the cheapest tour starting and ending at city 0 that visits every city exactly once.

HINTS — 6 IDEAS
  1. The state is (visited_set, current_city) — a bitmask plus an index. Everything about how you got there is irrelevant.
  2. dp[mask][u] = the cheapest way to have visited exactly mask and be standing at u.
  3. Start with dp[1][0] = 0: only city 0 visited, standing on it, nothing spent.
  4. Transition: from (mask, u), move to any unvisited v, reaching (mask | 1<<v, v) for dp[mask][u] + dist[u][v].
  5. Iterate masks in increasing order — adding a city only ever sets a bit, so a state is always finished before anything reads it.
  6. The answer closes the loop: min over u of dp[full][u] + dist[u][0]. Forgetting the return leg is the classic mistake.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextDigit DP: Count by Digits Next on the “When the state is not a number” ladder · rung 3 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms