Bitmasking
Bitmasking is a technique that uses the bits of an integer to store and manipulate information. Each bit represents a particular state, such as whether an element is selected, whether a permission is enabled, or whether a task has been completed. Using bitwise operators, we can check, set, clear, and toggle these states efficiently. Bitmasking is especially useful in subset problems and advanced dynamic programming.
1. What Is Bitmasking?
Bitmasking means using the binary representation of a number as a collection of flags. Each bit represents one independent condition or element.
Consider five elements: A, B, C, D, and E. We can represent whether each element is selected using five bits.
| Element | Bit Position | Bit Value |
|---|---|---|
| A | 0 | 1 |
| B | 1 | 2 |
| C | 2 | 4 |
| D | 3 | 8 |
| E | 4 | 16 |
Suppose the binary mask is:
Mask = 10101
Reading from right to left, the bits are:
Position: 4 3 2 1 0
Bit: 1 0 1 0 1
This means A, C, and E are selected, while B and D are not selected.
2. Why Do We Use Bitmasking?
Normally, we might use an array of Boolean values to represent whether several elements are selected.
For example:
bool selected[5] = {
true,
false,
true,
false,
true
};
The same information can be stored in a single integer:
int mask = 10101;
The second example is only showing the binary pattern conceptually; in actual C++ code, we can write it using a binary literal:
int mask = 0b10101;
This representation is compact and makes it easy to perform operations on multiple states using bitwise operators.
Advantages of Bitmasking
- Stores multiple Boolean states inside one integer.
- Uses less memory than many separate Boolean variables in suitable situations.
- Allows fast checking and updating of individual bits.
- Makes subset representation convenient.
- Is useful in dynamic programming and combinatorial problems.
3. Understanding Bit Positions
Bit positions are counted from right to left, starting at position 0. The rightmost bit is called the least significant bit (LSB).
Consider the binary number 10110:
Binary: 1 0 1 1 0
Position: 4 3 2 1 0
| Position | Bit | Place Value |
|---|---|---|
| 0 | 0 | 20 = 1 |
| 1 | 1 | 21 = 2 |
| 2 | 1 | 22 = 4 |
| 3 | 0 | 23 = 8 |
| 4 | 1 | 24 = 16 |
The value of a bit at position i is:
2i
4. Creating a Bitmask
To create a mask with a particular bit set, we use the left shift operator.
1 << i
This shifts the binary value 1 to the left by i positions. The result contains exactly one set bit at position i.
Examples
| Expression | Binary Result | Decimal Result |
|---|---|---|
| 1 << 0 | 00001 | 1 |
| 1 << 1 | 00010 | 2 |
| 1 << 2 | 00100 | 4 |
| 1 << 3 | 01000 | 8 |
| 1 << 4 | 10000 | 16 |
C++ Example
#include <iostream>
using namespace std;
int main() {
int position = 3;
int mask = 1 << position;
cout << "Mask: " << mask;
return 0;
}
Mask: 8
The expression 1 << 3 creates the binary mask 01000. Only bit position 3 is set.
5. Checking Whether a Bit Is Set
One of the most common bitmasking operations is checking whether a particular bit is 1 or 0.
We use the bitwise AND operator:
mask & (1 << i)
If the result is non-zero, the bit at position i is set. If the result is zero, the bit is not set.
Example
Suppose:
mask = 10110
i = 2
1 << 2 = 00100
Now perform AND:
10110
& 00100
--------
00100
The result is non-zero, so bit position 2 is set.
C++ Code
#include <iostream>
using namespace std;
bool isSet(int mask, int position) {
return (mask & (1 << position)) != 0;
}
int main() {
int mask = 0b10110;
int position = 2;
if (isSet(mask, position)) {
cout << "Bit is set";
} else {
cout << "Bit is not set";
}
return 0;
}
Bit is set
6. Setting a Bit
Setting a bit means changing its value to 1, regardless of whether it was previously 0 or 1.
We use the bitwise OR operator:
mask = mask | (1 << i)
OR with a mask containing one set bit changes that particular bit to 1 while keeping all other bits unchanged.
Example
Original mask = 10010
Position = 2
Bit mask = 00100
Perform OR:
10010
| 00100
--------
10110
The bit at position 2 has changed from 0 to 1.
C++ Code
#include <iostream>
using namespace std;
int setBit(int mask, int position) {
return mask | (1 << position);
}
int main() {
int mask = 0b10010;
int position = 2;
mask = setBit(mask, position);
cout << "Updated mask: " << mask;
return 0;
}
Updated mask: 22
7. Clearing a Bit
Clearing a bit means changing its value to 0, regardless of whether it was previously 0 or 1.
We use bitwise AND with the complement of the bit mask:
mask = mask & ~(1 << i)
The tilde (~) operator is the bitwise NOT operator. It changes every bit in the mask to its opposite value.
Example
Original mask = 10110
Position = 2
Bit mask = 00100
Complement = ...11011
After applying AND:
10110
& 11011
--------
10010
The bit at position 2 becomes 0. The other bits remain unchanged.
C++ Code
#include <iostream>
using namespace std;
int clearBit(int mask, int position) {
return mask & ~(1 << position);
}
int main() {
int mask = 0b10110;
int position = 2;
mask = clearBit(mask, position);
cout << "Updated mask: " << mask;
return 0;
}
Updated mask: 18
8. Toggling a Bit
Toggling a bit means changing 0 to 1 or changing 1 to 0.
We use the XOR operator:
mask = mask ^ (1 << i)
Example
Suppose:
Original mask = 10110
Position = 2
Bit mask = 00100
Apply XOR:
10110
^ 00100
--------
10010
The bit at position 2 was 1, so it becomes 0. If it had been 0, it would have become 1.
C++ Code
#include <iostream>
using namespace std;
int toggleBit(int mask, int position) {
return mask ^ (1 << position);
}
int main() {
int mask = 0b10110;
int position = 2;
mask = toggleBit(mask, position);
cout << "Updated mask: " << mask;
return 0;
}
Updated mask: 18
9. Summary of Basic Bitmasking Operations
| Operation | Expression | Purpose |
|---|---|---|
| Check | mask & (1 << i) | Check whether bit i is set |
| Set | mask | (1 << i) | Make bit i equal to 1 |
| Clear | mask & ~(1 << i) | Make bit i equal to 0 |
| Toggle | mask ^ (1 << i) | Reverse bit i |
10. Representing Sets Using Bitmasks
One of the most important applications of bitmasking is representing subsets of a collection.
Suppose we have a set containing three elements:
Set = {A, B, C}
Each element gets a bit position:
A = bit 0
B = bit 1
C = bit 2
A bit value of 1 means that the element is included in the subset. A bit value of 0 means that it is not included.
All Possible Subsets
A set containing n elements has 2n possible subsets. For three elements, there are 23 = 8 subsets.
| Mask | Binary | Selected Elements |
|---|---|---|
| 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} |
Every integer from 0 to 2n - 1 represents one unique subset of the original set.
11. Problem 1: Generate All Subsets Using Bitmasking
Problem Statement
Given an array of distinct elements, generate all possible subsets of the array.
Input = [1, 2, 3]
Output =
{ }
{1}
{2}
{1, 2}
{3}
{1, 3}
{2, 3}
{1, 2, 3}
Approach
- Let n be the number of elements in the array.
- There are 2n possible subsets.
- Generate masks from 0 to 2n - 1.
- For each mask, check every bit position.
- If a bit is set, include the corresponding array element.
- Print the subset.
Dry Run
Consider the array:
arr = [1, 2, 3]
For mask 5:
Mask = 5 = 101
Bit 0 = 1, so include arr[0] = 1
Bit 1 = 0, so skip arr[1] = 2
Bit 2 = 1, so include arr[2] = 3
Subset = {1, 3}
C++ Code
#include <iostream>
#include <vector>
using namespace std;
void generateSubsets(vector<int>& arr) {
int n = arr.size();
int total = 1 << n;
for (int mask = 0; mask < total; mask++) {
cout << "{ ";
for (int i = 0; i < n; i++) {
if (mask & (1 << i)) {
cout << arr[i] << " ";
}
}
cout << "}" << endl;
}
}
int main() {
vector<int> arr = {1, 2, 3};
generateSubsets(arr);
return 0;
}
Output
{ }
{ 1 }
{ 2 }
{ 1 2 }
{ 3 }
{ 1 3 }
{ 2 3 }
{ 1 2 3 }
Complexity Analysis
- Time Complexity: O(n × 2n), because there are 2n masks and we check n positions for each mask.
- Auxiliary Space Complexity: O(1), excluding the output, because we use only a fixed number of variables.
12. Problem 2: Check Whether a Subset Contains an Element
Problem Statement
Given a bitmask representing a subset, check whether the element at a particular position is included.
Mask = 10101
Check position = 2
Result = Yes
Approach
Use the AND operation between the mask and a value containing only the bit at the required position.
mask & (1 << position)
C++ Code
#include <iostream>
using namespace std;
bool containsElement(int mask, int position) {
return (mask & (1 << position)) != 0;
}
int main() {
int mask = 0b10101;
int position = 2;
if (containsElement(mask, position)) {
cout << "Element is present";
} else {
cout << "Element is absent";
}
return 0;
}
Element is present
Complexity Analysis
- Time Complexity: O(1), because only a fixed number of bitwise operations are performed.
- Space Complexity: O(1).
13. Problem 3: Count the Number of Selected Elements
Problem Statement
Given a bitmask, count how many elements are selected. This is equivalent to counting the number of set bits.
Mask = 101101
Set bits = 4
Selected elements = 4
Approach
We can examine each bit using right shifts and the AND operator. Another option is Brian Kernighan's algorithm, which removes one set bit in every iteration.
C++ Code Using Brian Kernighan's Algorithm
#include <iostream>
using namespace std;
int countSelected(unsigned int mask) {
int count = 0;
while (mask > 0) {
mask = mask & (mask - 1);
count++;
}
return count;
}
int main() {
unsigned int mask = 0b101101;
cout << "Selected elements: "
<< countSelected(mask);
return 0;
}
Selected elements: 4
Complexity Analysis
- Time Complexity: O(k), where k is the number of set bits.
- Space Complexity: O(1).
14. Problem 4: Check Whether All Elements Are Selected
Problem Statement
Given a collection of n elements represented by a bitmask, check whether every element is selected.
A mask with all n bits set can be constructed as:
(1 << n) - 1
Example
n = 4
All-selected mask = 1111
Decimal value = 15
If the given mask is equal to this value, all four elements are selected.
C++ Code
#include <iostream>
using namespace std;
bool allSelected(unsigned int mask, int n) {
unsigned int fullMask = (1u << n) - 1;
return mask == fullMask;
}
int main() {
unsigned int mask = 0b1111;
int n = 4;
if (allSelected(mask, n)) {
cout << "All elements are selected";
} else {
cout << "Some elements are not selected";
}
return 0;
}
All elements are selected
This example assumes n is within the valid shift range of unsigned int. For a 32-bit unsigned int, n must be less than 32.
15. Combining Two Bitmasks
We can use bitwise operators to combine two subsets or collections of selected states.
Union Using OR
The OR operator combines the selected bits from both masks.
A = 00101
B = 01100
A | B = 01101
Intersection Using AND
The AND operator keeps only the bits that are set in both masks.
A = 00101
B = 01100
A & B = 00100
Symmetric Difference Using XOR
XOR keeps the bits that are set in exactly one of the two masks.
A = 00101
B = 01100
A ^ B = 01001
| Operation | Operator | Meaning |
|---|---|---|
| Union | | | Selected in either mask |
| Intersection | & | Selected in both masks |
| Symmetric Difference | ^ | Selected in exactly one mask |
16. Important Applications of Bitmasking
1. Subset Generation
Bitmasks allow us to represent every possible subset of a small collection using an integer. This is useful in combinatorial problems and subset enumeration.
2. Dynamic Programming
In bitmask dynamic programming, a mask can represent which elements have already been selected, visited, or completed. The mask becomes part of the DP state.
3. Permission Systems
Different permissions can be represented by different bits. For example, one bit can represent read permission, another can represent write permission, and another can represent execute permission.
4. Game State Representation
In games involving a small number of objects or positions, a bitmask can represent which objects are available, occupied, or already visited.
5. Efficient State Storage
When many Boolean states must be stored together, bitmasking can provide a compact representation and fast bitwise updates.
17. Common Mistakes in Bitmasking
- Starting bit positions from 1: Bit positions normally start from 0, with the rightmost bit at position 0.
- Using AND instead of OR to set a bit: Setting a bit is done using OR.
- Using OR to clear a bit: Clearing a bit requires AND with the complemented mask.
- Confusing toggle and set: XOR toggles a bit, while OR sets it.
-
Forgetting parentheses:
Write
mask & (1 << i)clearly to make the intended operation easy to understand. - Shifting by an invalid amount: In C++, shifting by a negative amount or by an amount greater than or equal to the width of the promoted left operand produces undefined behavior.
- Using a signed integer carelessly: For masks, unsigned integer types are often safer, especially when working with high bit positions.
- Assuming a mask can represent unlimited elements: The number of available bit positions depends on the integer type being used.
18. Time and Space Complexity Summary
| Operation | Time Complexity | Extra Space |
|---|---|---|
| Check a bit | O(1) | O(1) |
| Set a bit | O(1) | O(1) |
| Clear a bit | O(1) | O(1) |
| Toggle a bit | O(1) | O(1) |
| Count set bits using Kernighan's algorithm | O(k) | O(1) |
| Generate all subsets | O(n × 2n) | O(1) auxiliary |
| Combine two masks | O(1) | O(1) |
Here, n is the number of elements and k is the number of set bits. The subset-generation complexity excludes the time needed to store or print the output.
19. Interview Questions
Q1. What is bitmasking?
Bitmasking is a technique that uses bits of an integer to represent and manipulate multiple Boolean states.
Q2. What is a bitmask?
A bitmask is a binary pattern in which each bit represents the state of a particular element or condition.
Q3. How do you check whether a bit is set?
Use mask & (1 << i). A non-zero result
means that bit i is set.
Q4. How do you set a bit?
Use mask | (1 << i).
Q5. How do you clear a bit?
Use mask & ~(1 << i).
Q6. How do you toggle a bit?
Use mask ^ (1 << i).
Q7. How many subsets can be formed from n elements?
There are 2n possible subsets, including the empty subset and the complete set.
Q8. How can we generate all subsets using bitmasking?
Generate masks from 0 to 2n - 1. For each mask, include the elements whose corresponding bits are set.
Q9. What is the difference between setting and toggling a bit?
Setting always makes a bit 1. Toggling changes 0 to 1 and 1 to 0.
Q10. What is the relationship between bitmasking and bitmask DP?
Bitmasking provides a compact way to represent a set of states. Bitmask DP uses that representation as part of a dynamic programming state to solve problems involving subsets.
20. Practice Problems
- Create a mask with only bit position 4 set.
- Check whether bit position 3 is set in a given number.
- Set bit position 2 in the number 8.
- Clear bit position 1 in the number 15.
- Toggle bit position 3 in the number 10.
- Count the set bits in a given integer.
- Generate all subsets of an array containing four distinct elements.
- Find the union of two bitmasks.
- Find the intersection of two bitmasks.
- Check whether all bits in a mask are set for a given number of elements.
- Represent a collection of permissions using a bitmask.
- Write a program that adds and removes elements from a bitmask-based set.
21. Quick Revision
- Bitmasking stores multiple states inside the bits of an integer.
- Bit positions start from 0 at the rightmost bit.
1 << icreates a mask with bit i set.mask & (1 << i)checks a bit.mask | (1 << i)sets a bit.mask & ~(1 << i)clears a bit.mask ^ (1 << i)toggles a bit.- A collection of n elements has 2n possible subsets.
- Every subset can be represented by one mask from 0 to 2n - 1.
- Bitmasking is an important foundation for bitmask dynamic programming.
Conclusion
Bitmasking is a useful technique for storing and manipulating multiple Boolean states using a single integer. By combining left shifts with AND, OR, XOR, and NOT, we can check, set, clear, and toggle individual bits efficiently.
One of the most important applications is generating all subsets of a collection. Understanding how each bit represents an element will make it easier to solve more advanced problems involving subsets and dynamic programming.
In the next topic, we will study Bitmask DP (Intermediate to Advanced). We will learn how bitmasks can be combined with dynamic programming to represent visited elements, selected subsets, and states in problems such as assignment and travelling through a collection of nodes.