Challenge - 5 Problems
Bitmask Subsets Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of subsets generated by bitmask
What is the output of the following C++ code that generates all subsets of {1, 2} using bitmask?
DSA C++
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = {1, 2}; int n = nums.size(); for (int mask = 0; mask < (1 << n); ++mask) { cout << "{"; for (int i = 0; i < n; ++i) { if (mask & (1 << i)) { cout << nums[i] << " "; } } cout << "}\n"; } return 0; }
Attempts:
2 left
💡 Hint
Remember that bitmask from 0 to 2^n - 1 represents subsets, 0 means empty subset.
✗ Incorrect
The bitmask loops from 0 to 3 (2^2 - 1). For each bit set, the corresponding element is included. mask=0 means empty set, mask=1 means {1}, mask=2 means {2}, mask=3 means {1,2}.
🧠 Conceptual
intermediateNumber of subsets generated by bitmask
If you have a set with 5 elements, how many subsets will the bitmask method generate?
Attempts:
2 left
💡 Hint
Number of subsets of a set with n elements is 2^n.
✗ Incorrect
Each element can be either included or excluded, so total subsets = 2^5 = 32.
🔧 Debug
advancedIdentify the error in subset generation code
What error will the following code produce when generating subsets using bitmask for vector nums = {1, 2, 3}?
int n = nums.size();
for (int mask = 0; mask <= (1 << n); ++mask) {
for (int i = 0; i <= n; ++i) {
if (mask & (1 << i)) {
cout << nums[i] << " ";
}
}
cout << "\n";
Attempts:
2 left
💡 Hint
Check the loop condition for mask and how many subsets are generated.
✗ Incorrect
The loop runs mask from 0 to (1 << n) inclusive, which is 2^n + 1 iterations. The last mask value equals 2^n, which has a bit set at position n, causing out of range access in nums[i].
❓ Predict Output
advancedOutput of subsets with sum calculation
What is the output of the following code that prints subsets of {1, 3} and their sums using bitmask?
DSA C++
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = {1, 3}; int n = nums.size(); for (int mask = 0; mask < (1 << n); ++mask) { int sum = 0; cout << "Subset: {"; for (int i = 0; i < n; ++i) { if (mask & (1 << i)) { cout << nums[i] << " "; sum += nums[i]; } } cout << "} Sum: " << sum << "\n"; } return 0;
Attempts:
2 left
💡 Hint
Bitmask from 0 to 3 generates subsets in order: empty, {1}, {3}, {1,3}.
✗ Incorrect
mask=0 no bits set sum=0, mask=1 includes 1 sum=1, mask=2 includes 3 sum=3, mask=3 includes 1 and 3 sum=4.
🧠 Conceptual
expertBitmask subset generation with duplicate elements
Given a vector nums = {1, 2, 2}, how many subsets will the bitmask method generate?
Attempts:
2 left
💡 Hint
Bitmask generates 2^3 = 8 subsets even with duplicate elements.
✗ Incorrect
Bitmask generates 2^3=8 subsets including duplicates. Unique subsets are fewer but bitmask does not filter duplicates.
