Bitmask DP (State Compression)
Software Engineer path · lesson 38 of 99Use bits to represent subset states, enabling DP over all subsets efficiently. Essential for Travelling Salesman, subset selection, and assignment problems.
2–4 cities; city 0 is the start. Symmetric distances read best.
Start at city 0 with only city 0 visited: dp[0001][0] = 0.
- 1dp[{0}][0] = 0 # start at city 0
- 2for mask in increasing order, for last in mask:
- 3 for next not in mask:
- 4 m2 = mask | (1 << next)
- 5 dp[m2][next] = min(dp[m2][next], dp[mask][last] + d[last][next])
- 6answer = min over last of dp[all][last] + d[last][0]
- Transitions
- 0 / 15
- Improvements
- 0 / 14
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Subsets as integers
Sort each bitmask expression by what it does to the subset.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
Test membership
Drop items hereAdd an element
Drop items hereRemove an element
Drop items hereTest your knowledge
How do you iterate over all subsets of a bitmask m?
The short version
Imagine tracking which cities a salesman has visited using light switches. Each switch ON/OFF represents visited/not visited. Instead of storing lists, you store a single number whose binary bits encode the entire state.
In more depth
Subsets as Numbers
A bitmask of n bits can represent all 2^n subsets of n elements.
Common Operations:
mask & (1 << i)mask | (1 << i)mask & ~(1 << i)for (s = m; s > 0; s = (s-1) & m)TSP Pattern:
dp[mask][i] = min cost to visit cities in 'mask' ending at city i
Key Gotchas:
When to reach for this
- Visit all nodes exactly once (TSP/Hamiltonian Path)
- Select k items from n with complex constraints
- n is small (≤ 20) and need to consider all subsets
- Keywords: 'all possible subsets', 'assignment problem'
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required