Bitmask DP (Intermediate to Advanced)
Bitmask Dynamic Programming is an advanced algorithmic technique that combines bit manipulation with dynamic programming. It is especially useful when a problem involves a small number of elements and we need to remember which elements have already been selected, visited, assigned, or processed. Instead of storing a separate Boolean value for every element, we represent the complete selection using a single integer called a bitmask. This bitmask becomes part of our DP state and helps us solve complex subset and optimization problems efficiently.
1. What Is Bitmask DP?
Bitmask DP means using a bitmask to represent a state in dynamic programming.
A bitmask is a binary number in which each bit represents the status of one element. A bit can be:
- 1: The corresponding element is selected, visited, or completed.
- 0: The corresponding element is not selected, visited, or completed.
For example, suppose we have four tasks: A, B, C, and D. We can represent which tasks are completed using four bits.
Mask = 0101
A = 1: Completed
B = 0: Not completed
C = 1: Completed
D = 0: Not completed
This means tasks A and C are completed, while B and D are still pending.
2. Why Do We Need Bitmask DP?
Consider a problem where we have to choose a subset of elements. We need to remember which elements have already been selected.
One simple method is to use a Boolean array:
bool selected[4] = {
true,
false,
true,
false
};
This works, but when the number of elements is small, we can represent the same information using a single integer.
int mask = 5; // Binary: 0101
Each bit represents one element. This makes it easy to check whether an element is selected and to update the selection.
Advantages of Bitmask DP
- Uses a compact representation of selected elements.
- Allows fast checking and updating of element status.
- Can represent all subsets of a small set.
- Works well with dynamic programming and memoization.
- Helps solve many subset and assignment optimization problems.
3. Understanding Bitmask Representation
Suppose we have four elements:
Elements = [A, B, C, D]
We need four bits to represent the selected status of these elements.
| Mask | Binary | Selected Elements |
|---|---|---|
| 0 | 0000 | None |
| 1 | 0001 | A |
| 2 | 0010 | B |
| 3 | 0011 | A, B |
| 4 | 0100 | C |
| 5 | 0101 | A, C |
| 6 | 0110 | B, C |
| 7 | 0111 | A, B, C |
| 8 | 1000 | D |
| 9 | 1001 | A, D |
| 10 | 1010 | B, D |
| 15 | 1111 | A, B, C, D |
With four elements, we can represent 24 = 16 different subsets.
In general, for n elements, the total number of possible bitmasks is:
Total Masks = 2n
4. Bitwise Operations Used in Bitmask DP
Before writing Bitmask DP solutions, we should understand the operations used to manipulate individual bits.
1. Check Whether an Element Is Selected
To check whether the bit at position i is set, use:
mask & (1 << i)
If the result is non-zero, the element is selected. Otherwise, it is not selected.
if (mask & (1 << i)) {
cout << "Selected";
} else {
cout << "Not Selected";
}
2. Add an Element to the Mask
To mark the element at position i as selected, use bitwise OR:
mask = mask | (1 << i)
mask |= (1 << i);
3. Remove an Element From the Mask
To clear the bit at position i, use AND with the complement of the bit mask:
mask = mask & ~(1 << i)
mask &= ~(1 << i);
4. Toggle an Element
To change a bit from 0 to 1 or from 1 to 0, use XOR:
mask = mask ^ (1 << i)
mask ^= (1 << i);
5. Count Selected Elements
We can count the number of set bits using the C++20 std::popcount() function.
#include <bit>
int selectedCount = popcount(
static_cast<unsigned int>(mask)
);
If C++20 is unavailable, we can count set bits using a loop or a compiler-supported built-in function.
5. Understanding All Possible Subsets
One important idea in Bitmask DP is that every possible subset can be represented by an integer between 0 and 2n - 1.
Suppose we have three elements: A, B, and C.
| Mask | Binary | Subset |
|---|---|---|
| 0 | 000 | { } |
| 1 | 001 | { A } |
| 2 | 010 | { B } |
| 3 | 011 | { A, B } |
| 4 | 100 | { C } |
| 5 | 101 | { A, C } |
| 6 | 110 | { B, C } |
| 7 | 111 | { A, B, C } |
C++ Code to Generate All Subsets
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<char> arr = {'A', 'B', 'C'};
int n = arr.size();
int totalMasks = 1 << n;
for (int mask = 0; mask < totalMasks; mask++) {
cout << "{ ";
for (int i = 0; i < n; i++) {
if (mask & (1 << i)) {
cout << arr[i] << " ";
}
}
cout << "}" << endl;
}
return 0;
}
{ }
{ A }
{ B }
{ A B }
{ C }
{ A C }
{ B C }
{ A B C }
This program generates every subset exactly once.
Complexity Analysis
- Time Complexity: O(n × 2n), because there are 2n masks and we check n bits for each mask.
- Space Complexity: O(1) auxiliary space, excluding the input array and output.
6. What Is the DP State in Bitmask DP?
In normal dynamic programming, a state describes the information needed to solve a smaller subproblem.
In Bitmask DP, the state often includes a mask representing which elements have already been processed.
For example:
dp[mask]
Meaning: Best answer for the subset represented by mask.
Sometimes, we need additional information such as the current position, the last visited city, or the number of completed tasks.
dp[mask][last]
Meaning: Best answer after visiting the subset mask
and ending at element last.
Example of a DP State
Suppose we have four cities. A state:
dp[0101][2]
can mean that we have visited cities 0 and 2, and our current position is city 2.
7. Problem 1: Minimum Cost to Assign Jobs
Problem Statement
There are n workers and n jobs. Every worker can perform every job, but the cost of assigning a particular job to a particular worker is different.
We need to assign exactly one job to every worker and exactly one worker to every job. Find the minimum total assignment cost.
Example
Consider the following cost matrix:
| Worker | Job 0 | Job 1 | Job 2 |
|---|---|---|---|
| Worker 0 | 9 | 2 | 7 |
| Worker 1 | 6 | 4 | 3 |
| Worker 2 | 5 | 8 | 1 |
We need to choose one job for each worker without assigning the same job twice.
Possible Assignment
- Worker 0 gets Job 1, costing 2.
- Worker 1 gets Job 0, costing 6.
- Worker 2 gets Job 2, costing 1.
Total Cost = 2 + 6 + 1 = 9
This is the minimum possible assignment cost for this example.
How Does Bitmask DP Help?
We use a mask to represent which jobs have already been assigned. If bit i is set, job i has already been assigned.
Define:
dp[mask] = Minimum cost after assigning the jobs
represented by mask to the first k workers.
k = number of set bits in mask.
We do not need a separate worker index because the number of assigned jobs tells us how many workers have already received a job.
Transition
Suppose the current mask represents the assigned jobs. We can assign any job j that is not already selected.
newMask = mask | (1 << j)
newCost = dp[mask] + cost[k][j]
We update the new state if the new cost is smaller than the previously stored cost.
C++ Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int minimumAssignmentCost(
const vector<vector<int>>& cost
) {
int n = cost.size();
int totalMasks = 1 << n;
const int INF = INT_MAX / 2;
vector<int> dp(totalMasks, INF);
dp[0] = 0;
for (int mask = 0; mask < totalMasks; mask++) {
if (dp[mask] == INF) {
continue;
}
int worker = __builtin_popcount(
static_cast<unsigned int>(mask)
);
if (worker == n) {
continue;
}
for (int job = 0; job < n; job++) {
if ((mask & (1 << job)) == 0) {
int newMask = mask | (1 << job);
int newCost =
dp[mask] + cost[worker][job];
dp[newMask] = min(
dp[newMask],
newCost
);
}
}
}
return dp[totalMasks - 1];
}
int main() {
vector<vector<int>> cost = {
{9, 2, 7},
{6, 4, 3},
{5, 8, 1}
};
cout << "Minimum Assignment Cost: "
<< minimumAssignmentCost(cost);
return 0;
}
Minimum Assignment Cost: 9
Complexity Analysis
- Time Complexity: O(n × 2n), because there are 2n masks and we may examine n possible jobs for each mask.
- Space Complexity: O(2n), because we store one DP value for every mask.
8. Problem 2: Travelling Salesperson Problem Using Bitmask DP
Problem Statement
A salesperson needs to visit n cities exactly once and return to the starting city. The travel cost between every pair of cities is given.
Find the minimum total travel cost.
Example
Consider four cities with the following cost matrix:
| City | City 0 | City 1 | City 2 | City 3 |
|---|---|---|---|---|
| City 0 | 0 | 10 | 15 | 20 |
| City 1 | 10 | 0 | 35 | 25 |
| City 2 | 15 | 35 | 0 | 30 |
| City 3 | 20 | 25 | 30 | 0 |
One Optimal Route
City 0 → City 1 → City 3 → City 2 → City 0
Cost = 10 + 25 + 30 + 15
Minimum Cost = 80
DP State
We define:
dp[mask][last]
Minimum cost to start from city 0,
visit all cities in mask,
and finish at city last.
Here:
- mask: Represents the cities already visited.
- last: Represents the current city.
Initial State
We start from city 0. Therefore, only city 0 is visited initially.
dp[0001][0] = 0
Transition
From the current city last, we try to visit every city next that has not been visited.
newMask = mask | (1 << next)
newCost = dp[mask][last] + cost[last][next]
We keep the minimum cost for every new state.
Final Answer
Once all cities have been visited, we return to city 0. Therefore, we calculate:
Answer = min over last:
dp[allVisited][last] + cost[last][0]
C++ Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int travellingSalesperson(
const vector<vector<int>>& cost
) {
int n = cost.size();
int totalMasks = 1 << n;
const int INF = INT_MAX / 2;
vector<vector<int>> dp(
totalMasks,
vector<int>(n, INF)
);
// Start from city 0.
dp[1][0] = 0;
for (int mask = 0; mask < totalMasks; mask++) {
for (int last = 0; last < n; last++) {
if (dp[mask][last] == INF) {
continue;
}
for (int next = 0; next < n; next++) {
// Skip cities already visited.
if (mask & (1 << next)) {
continue;
}
int newMask =
mask | (1 << next);
int newCost =
dp[mask][last] + cost[last][next];
dp[newMask][next] = min(
dp[newMask][next],
newCost
);
}
}
}
int allVisited = totalMasks - 1;
int answer = INF;
// Return to starting city 0.
for (int last = 0; last < n; last++) {
if (dp[allVisited][last] != INF) {
answer = min(
answer,
dp[allVisited][last] + cost[last][0]
);
}
}
return answer;
}
int main() {
vector<vector<int>> cost = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
cout << "Minimum Travel Cost: "
<< travellingSalesperson(cost);
return 0;
}
Minimum Travel Cost: 80
Complexity Analysis
- Time Complexity: O(n2 × 2n), because each mask may be combined with every current city and every possible next city.
- Space Complexity: O(n × 2n), because the DP table stores a value for every mask and ending city.
9. Problem 3: Count Ways to Assign Tasks
Problem Statement
Suppose there are n workers and n tasks. Each worker can perform any task. We need to count the number of ways to assign exactly one task to each worker, with each task assigned to only one worker.
For n workers and n distinct tasks, the number of possible assignments is n factorial. We can calculate this using Bitmask DP.
DP State
dp[mask] = Number of ways to assign
the tasks represented by mask
to the first popcount(mask) workers.
Transition
If k tasks have already been assigned, the next worker is worker k. We can assign any task that is not yet selected.
dp[newMask] += dp[mask]
C++ Code
#include <iostream>
#include <vector>
using namespace std;
long long countAssignments(int n) {
int totalMasks = 1 << n;
vector<long long> dp(totalMasks, 0);
dp[0] = 1;
for (int mask = 0; mask < totalMasks; mask++) {
int worker = __builtin_popcount(
static_cast<unsigned int>(mask)
);
if (worker == n) {
continue;
}
for (int task = 0; task < n; task++) {
if ((mask & (1 << task)) == 0) {
int newMask =
mask | (1 << task);
dp[newMask] += dp[mask];
}
}
}
return dp[totalMasks - 1];
}
int main() {
int n = 3;
cout << "Number of Assignments: "
<< countAssignments(n);
return 0;
}
Number of Assignments: 6
For three workers and three distinct tasks, there are:
3! = 3 × 2 × 1 = 6 assignments
Complexity Analysis
- Time Complexity: O(n × 2n).
- Space Complexity: O(2n).
10. General Template for Bitmask DP
Many Bitmask DP problems follow a similar structure:
- Determine how many elements are involved.
- Represent the selected elements using a bitmask.
- Define the DP state and what it represents.
- Initialize the starting state.
- Try adding each element that has not been selected.
- Update the corresponding DP state.
- Return the final answer from the required state.
Generic C++ Template
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 4;
int totalMasks = 1 << n;
vector<int> dp(totalMasks, 0);
// Initial state.
dp[0] = 1;
for (int mask = 0; mask < totalMasks; mask++) {
for (int i = 0; i < n; i++) {
// Check whether element i is not selected.
if ((mask & (1 << i)) == 0) {
int newMask =
mask | (1 << i);
// Example state update.
dp[newMask] += dp[mask];
}
}
}
cout << "Ways: "
<< dp[totalMasks - 1];
return 0;
}
This is a general subset-state transition pattern. The exact DP value, initialization, and transition must be changed according to the problem being solved.
11. How to Identify a Bitmask DP Problem
Not every dynamic programming problem needs bitmasking. We generally consider Bitmask DP when the problem has a small number of elements and needs to track subsets.
Common Signs
- The problem asks us to visit every city exactly once.
- We need to assign unique jobs to workers.
- We need to select elements without repeating them.
- We need to remember which tasks are completed.
- The problem involves subsets of a small set.
- The solution requires remembering both a subset and another state such as the current position.
12. Complexity of Bitmask DP
The number of possible masks for n elements is 2n. This is why Bitmask DP is normally used when n is relatively small.
| Number of Elements (n) | Number of Masks (2n) |
|---|---|
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
| 10 | 1,024 |
| 15 | 32,768 |
| 20 | 1,048,576 |
| 25 | 33,554,432 |
Common Complexity Patterns
| DP Pattern | Time Complexity | Space Complexity |
|---|---|---|
| Simple subset DP | O(2n) | O(2n) |
| Subset with one transition loop | O(n × 2n) | O(2n) |
| Assignment DP | O(n × 2n) | O(2n) |
| Travelling Salesperson DP | O(n2 × 2n) | O(n × 2n) |
13. Common Mistakes in Bitmask DP
- Using the wrong number of masks: For n elements, the total number of masks is 2n, and valid masks range from 0 to 2n - 1.
- Incorrect bit positions: The first element is normally represented by bit 0, the second by bit 1, and so on.
- Forgetting to check whether an element is selected: We must avoid selecting the same element more than once when the problem requires unique selections.
- Incorrect DP initialization: The starting state must match the meaning of the DP. For example, a minimum-cost problem often starts with dp[0] = 0.
- Incorrect transition: The new mask must include the newly selected element.
- Using an insufficient integer type: The number of ways or total costs may exceed the range of a regular int. Choose a suitable type.
- Ignoring memory limits: A DP array of size 2n grows quickly.
- Not defining the state clearly: Always explain what dp[mask] or dp[mask][last] means before writing the recurrence.
14. Bitmask DP vs Normal Dynamic Programming
| Feature | Normal DP | Bitmask DP |
|---|---|---|
| State representation | Indices, values, or other variables | Bitmask plus optional variables |
| Subset tracking | May require additional structures | Represented by bits |
| Typical input size | Can be large, depending on the problem | Usually small |
| Number of states | Depends on the DP definition | Often includes 2n masks |
| Common problems | Knapsack, Fibonacci, LCS | Assignment, TSP, subset optimization |
15. Interview Questions
Q1. What is Bitmask DP?
Bitmask DP is a dynamic programming technique that uses binary masks to represent subsets or the status of elements.
Q2. What is a bitmask?
A bitmask is a binary representation in which each bit represents the status of an element.
Q3. How many subsets can be formed from n elements?
There are 2n possible subsets, including the empty subset and the complete subset.
Q4. How do you check whether bit i is set?
Use the expression mask & (1 << i). A non-zero result means the bit is set.
Q5. How do you add an element to a mask?
Use mask | (1 << i).
Q6. How do you remove an element from a mask?
Use mask & ~(1 << i).
Q7. What does dp[mask] usually represent?
It represents a DP value for the subset represented by mask. The exact meaning depends on the problem.
Q8. Why is Bitmask DP suitable for small n?
Because it may need 2n states, which grows exponentially as n increases.
Q9. What is the state in the Travelling Salesperson Problem?
A common state is dp[mask][last], which represents the minimum cost to visit the cities in mask and finish at city last.
Q10. What is the time complexity of Bitmask DP for TSP?
The standard solution takes O(n2 × 2n) time and O(n × 2n) space.
16. Practice Problems
Solve these problems in order to strengthen your understanding of bitmasking and dynamic programming.
Beginner Level
- Generate all subsets of an array using bitmasks.
- Count the number of set bits in every mask from 0 to 2n - 1.
- Check whether a particular element belongs to a subset.
- Find the number of subsets of size k.
- Calculate the sum of every possible subset.
Intermediate Level
- Count the number of ways to assign n tasks to n workers.
- Find the minimum assignment cost using Bitmask DP.
- Find the maximum sum of a valid assignment.
- Count valid permutations using subset DP.
- Find the minimum cost to visit all cities.
Advanced Level
- Solve the Travelling Salesperson Problem using Bitmask DP.
- Find the minimum cost Hamiltonian path.
- Count Hamiltonian paths in a graph using subset DP.
- Solve a constrained task scheduling problem using masks.
- Combine Bitmask DP with shortest path algorithms.
17. Quick Revision
- Bitmask DP combines bit manipulation and dynamic programming.
- A bitmask represents the selected or visited elements.
- For n elements, there are 2n possible masks.
- Check a bit using mask & (1 << i).
- Set a bit using mask | (1 << i).
- Clear a bit using mask & ~(1 << i).
- Toggle a bit using mask ^ (1 << i).
- Count selected elements using popcount.
- dp[mask] stores a value associated with a subset.
- dp[mask][last] can store the best result for a subset ending at a particular element.
- Bitmask DP is useful when n is relatively small.
- Common applications include assignment problems and TSP.
Conclusion
Bitmask DP is an important advanced technique that combines the power of binary operations with dynamic programming. It allows us to represent subsets efficiently and use them as states in optimization and counting problems.
The most important concepts are understanding how a mask represents a subset, defining the DP state correctly, and creating transitions by adding elements that have not yet been selected.
Problems such as minimum job assignment and the Travelling Salesperson Problem demonstrate how Bitmask DP can solve complex problems with relatively small input sizes.
With this topic, we have completed all nine topics in Module 16 – Bit Manipulation. The module covered binary numbers, bitwise operators, shifts, bit manipulation operations, set-bit counting, powers of two, XOR problems, bitmasking, and Bitmask DP.