Introduction
Hello! In our last lesson, we mastered Interval DP, a pattern for solving problems on a contiguous range [i, j] by finding optimal split points. As we concluded, that pattern is powerful for sequence-based problems, but many challenges revolve around choosing an optimal arrangement or subset of items, not a contiguous block.
Today, we'll tackle exactly that. As previewed, this lesson introduces Bitmask DP, a technique specifically designed for problems where the state depends on a subset of items, and the total number of items, N, is small (typically N ≤ 20). Our learning goal is to apply bitmask DP to problems with small state spaces, using the Traveling Salesman Problem (TSP) as our canonical example.
You'll learn how to use a single integer—a bitmask—to efficiently represent the state of visited nodes, enabling a DP solution to a problem that is otherwise computationally infeasible. This is a classic pattern that demonstrates a deep understanding of state representation, crucial for Staff-level interviews.
1. Representing Subsets with Bitmasks
The core idea of Bitmask DP is not the dynamic programming itself, but the state representation. Many DP problems have subproblems defined by "the items we have used so far." For example, in the Traveling Salesman Problem, a subproblem is "the minimum path that visits a specific subset of cities and ends at city X."
The challenge is how to use this subset in our DP state for memoization. A list or a hash set is often not a valid or efficient key for a memoization table. This is where bitmasking shines.
If we have N items, we can use an N-bit integer (the "mask") where the i-th bit is 1 if the i-th item is in the subset, and 0 otherwise.
Set Representation using Bitmasking
The article 'Unmasking Bitmasked Dynamic Programming' provides a fantastic explanation of this core concept. Let's start there to build a solid foundation.
Please read the section titled 'Set Representation using Bitmasking'. It clearly illustrates how to map subsets of an array to their integer bitmask representations. Focus on the core idea: an integer is a compact, hashable, and efficient way to represent a subset for small N.
Since you'll be implementing this in Go, here are the essential bitwise operations you'll need:
- Check if the
i-th item is in the set:(mask >> i) & 1 == 1 - Add the
i-th item to the set:mask | (1 << i) - Remove the
i-th item from the set:mask ^ (1 << i)(This toggles the bit, useful if you know the bit is set).
2. Applying Bitmask DP to the Traveling Salesman Problem (TSP)
The Traveling Salesman Problem is the classic use case for Bitmask DP in an interview context.
Problem: You are given N cities and a matrix of distances between them. Find the shortest possible tour that visits each city exactly once and returns to the starting city.

A brute-force solution would involve trying all (N-1)! permutations of cities, which is too slow for N > 15. Dynamic programming can reduce this complexity significantly.
Defining the DP State
To make a decision about where to go next, what information do we need?
- The set of cities we have already visited.
- The city we are currently at (the end of the current path).
This leads us to the DP state:dp[mask][i] = The minimum cost of a path that starts at a designated city (e.g., city 0), visits all cities represented by the 1s in the mask, and ends at city i.
Top-Down Recursive Formulation
A top-down, recursive approach is often the most intuitive way to solve this in an interview. We can define a function solve(mask, current_city) that computes our DP state.
Travelling Salesman Problem using Dynamic Programming - Easiest Approach with Code
The video 'Travelling Salesman Problem using Dynamic Programming' from Coding Blocks gives a clear, step-by-step walkthrough of this recursive logic. It builds the intuition from the ground up.
Watch from 04:53 to 16:02. Pay close attention to: State Representation (04:53 - 11:17): How the mask tracks visited cities and current_city tracks the path's end. Base Case and Recursive Step (11:17 - 16:02): The logic for the base case (when all cities are visited) and how the recursive calls explore unvisited cities.
As the video illustrates, we are exploring different paths, and many of these paths will lead to the same subproblem (e.g., reaching city C after having visited the set {A, B}). This presence of overlapping subproblems is why we can use DP.

3. The Recurrence Relation and Complexity
Let's formalize the logic from the video into a recurrence relation.
To compute dp[mask][u], we consider all possible previous cities v that could have led to u. The city v must be in the set represented by mask, and we must have come from v to u. The path to v would have visited the cities in mask except for u.
The recurrence is:
-
Base Case: The path starts at city 0. The cost to be at city 0 having only visited city 0 is 0. So,
dp[1 << 0][0] = 0. All other initialdpvalues are infinity. -
Final Answer: After computing the
dptable for all states, the full tour must have visited all cities. The mask for this is(1 << N) - 1. The tour ends at some cityiand then must return to the start city (0).
Complexity Analysis
- State Space: There are possible masks and
Npossible ending cities. This gives states. - Transitions: For each state
(mask, u), the recurrence involves a loop overNpossible previous citiesv. - Total Time Complexity: .
- Space Complexity: for the memoization table.
This complexity is still exponential, but it's a massive improvement over and makes solutions for N up to around 20-22 feasible.
The USACO Guide provides a very concise summary of this solution structure and its complexity, which is great for reinforcing what we've just learned.
Read the 'Solution' section for the 'Hamiltonian Flights' problem. It presents the exact dp[S][i] formulation and time complexity we've discussed for TSP.
4. Implementation in Go
Now, let's put this all together in Go. A top-down recursive implementation with memoization is idiomatic and generally preferred in interviews for its clarity.
Here is a Go implementation based on the logic we've developed.
package main
import "math"
// Assuming N is the number of cities and dist is the N x N distance matrix.
// Let's assume city 0 is the starting city.
func solveTSP(dist [][]int) int {
N := len(dist)
memo := make([][]int, 1<<N)
for i := range memo {
memo[i] = make([]int, N)
for j := range memo[i] {
memo[i][j] = -1 // Use -1 to indicate not computed
}
}
// `solve` returns the min cost of a path visiting cities in `mask` and ending at `pos`
var solve func(mask int, pos int) int
solve = func(mask int, pos int) int {
// Base case: if only the starting city is in the mask, the path is just of length 0.
if mask == (1<<pos) {
// In a typical TSP starting from 0, this is dist[0][pos] but for the general
// recursive step, let's stick to the pure definition. We'll set the absolute base case outside.
// For a path from start, it would be dist[start_node][pos].
// Let's refine for a path starting at 0:
if pos == 0 {
return 0
}
return math.MaxInt32
}
if memo[mask][pos] != -1 {
return memo[mask][pos]
}
minCost := math.MaxInt32
// The previous city `prev` must be in the mask.
// The mask for the subproblem is the current mask without `pos`.
prevMask := mask ^ (1 << pos)
for prev := 0; prev < N; prev++ {
// Check if `prev` was in the previous sub-path
if (prevMask>>prev)&1 == 1 {
res := solve(prevMask, prev)
if res != math.MaxInt32 {
minCost = min(minCost, res + dist[prev][pos])
}
}
}
memo[mask][pos] = minCost
return minCost
}
// Set the absolute base case: the cost of the path visiting only city 0 and ending at 0 is 0.
memo[1][0] = 0
// After filling the memo table, find the final answer.
finalMask := (1 << N) - 1
minTourCost := math.MaxInt32
for i := 1; i < N; i++ {
tourEndCost := solve(finalMask, i)
if tourEndCost != math.MaxInt32 {
minTourCost = min(minTourCost, tourEndCost + dist[i][0])
}
}
return minTourCost
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
Note on the Go code: The recursive function computes the cost of paths starting at city 0. The final loop iterates through all possible second-to-last cities i, gets the cost of the tour ending at i, and adds the final leg back to city 0 to complete the cycle.
5. Staff+ Depth: Beyond the Basics
For a Staff-level role, showing you understand the boundaries and extensions of a pattern is key.
1. Path Reconstruction:
Finding the minimum cost is half the problem. To reconstruct the actual path, you need to store which previous node v led to the optimal dp[mask][u]. You can use a second table, parent[mask][u], to store this information. After finding the final cost, you can backtrack from the end state using the parent table to rebuild the optimal tour.
Traveling Salesman Problem | Dynamic Programming | Graph Theory
The WilliamFiset video on TSP provides a complete implementation, including logic for reconstructing the optimal tour. Let's quickly review that part.
Watch from 17:43 to 19:44. Focus on the findOptimalTour function. Notice how it works backward from the final state, iteratively finding the best previous node by checking which choice would have produced the stored minimum cost.
2. General Subset DP and the Trick:
Some problems require transitions not just from S \ {i} but from all subsets of a set S. The recurrence might look like dp[S] = min(dp[T] + dp[S \ T]) over all partitions T of S. A naive implementation is , but there's a clever bitwise trick to iterate through all submasks of a mask in a way that leads to an overall complexity.
// A common pattern for O(3^N) DP over subsets
for (int mask = 0; mask < (1 << n); mask++) {
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
// Here, 'submask' is a submask of 'mask'.
// The other part of the partition is `mask ^ submask`.
// dp[mask] = min(dp[mask], dp[submask] + dp[mask ^ submask]);
}
}
Knowing this pattern exists is a sign of deep algorithmic knowledge, even if you don't need to code it from scratch. The USACO Guide (LINK) mentions this in its "Merging Subsets" section.
Conclusion
Today we added a powerful and specialized tool to your DP arsenal: Bitmask DP.
Key Takeaways:
- Core Principle: Bitmask DP is used for problems involving permutations or subsets when the number of elements
Nis small (N ≤ 20). - State Representation: The key is to use an N-bit integer (a mask) to represent the subset of elements involved in a subproblem.
- TSP Formulation: The canonical DP state is
dp[mask][last_item], representing the optimal value for a subproblem covering items inmaskand ending atlast_item. - Complexity: The typical time complexity for TSP-like problems is , a huge improvement over factorial brute-force.
Preview of the Next Lesson:
We've now completed our deep dive into core and advanced DP patterns. You've seen how to handle sequences, grids, intervals, and now subsets. We will now shift gears in our next module, "Hard-Level Coding Problem Strategies." The first lesson will focus on a more general skill: how to decompose complex problems into solvable subproblems. This meta-skill is about identifying the underlying structure of a problem, which might involve DP, graphs, or a combination of patterns, and is absolutely essential for the Staff+ interview loop.