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 Java code that generates all subsets of the array [1, 2] using bitmask?
DSA Java
int[] nums = {1, 2}; for (int mask = 0; mask < (1 << nums.length); mask++) { System.out.print("{"); for (int i = 0; i < nums.length; i++) { if ((mask & (1 << i)) != 0) { System.out.print(nums[i] + ","); } } System.out.println("}"); }
Attempts:
2 left
💡 Hint
Think about how the bitmask counts from 0 to 2^n - 1 and which bits correspond to which elements.
✗ Incorrect
The bitmask runs from 0 to 3 (for 2 elements). For each mask, bits set to 1 include the corresponding element. Mask 0 includes none, mask 1 includes first element, mask 2 includes second element, mask 3 includes both.
🧠 Conceptual
intermediateNumber of subsets generated by bitmask
If you have an array of length 4, how many subsets will the bitmask method generate?
Attempts:
2 left
💡 Hint
Each element can be either included or excluded independently.
✗ Incorrect
For n elements, there are 2^n subsets. For 4 elements, 2^4 = 16 subsets.
🔧 Debug
advancedIdentify the error in subset generation code
What error does the following Java code produce when generating subsets using bitmask for array [1, 2, 3]?
int[] nums = {1, 2, 3};
for (int mask = 0; mask <= (1 << nums.length); mask++) {
System.out.print("{");
for (int i = 0; i < nums.length; i++) {
if ((mask & (1 << i)) != 0) {
System.out.print(nums[i] + ",");
}
}
System.out.println("}");
}
Attempts:
2 left
💡 Hint
Check the loop condition for mask and the maximum value it takes.
✗ Incorrect
The loop runs mask from 0 to (1 << nums.length) inclusive, which is 8 for length 3. But masks go from 0 to 7. When mask=8, bit operations access beyond array length causing ArrayIndexOutOfBoundsException.
❓ Predict Output
advancedOutput of subsets with empty subset excluded
What is the output of this Java code that generates all non-empty subsets of [1, 2, 3] using bitmask?
DSA Java
int[] nums = {1, 2, 3}; for (int mask = 1; mask < (1 << nums.length); mask++) { System.out.print("{"); for (int i = 0; i < nums.length; i++) { if ((mask & (1 << i)) != 0) { System.out.print(nums[i] + ","); } } System.out.println("}"); }
Attempts:
2 left
💡 Hint
Mask starts at 1, so empty subset is excluded.
✗ Incorrect
Masks from 1 to 7 generate all subsets except empty. The order is ascending mask value, so subsets appear in increasing size and bit pattern order.
🧠 Conceptual
expertBitmask subset generation complexity
What is the time complexity of generating all subsets of an array of length n using the bitmask method?
Attempts:
2 left
💡 Hint
Consider how many subsets and how many elements are checked per subset.
✗ Incorrect
There are 2^n subsets. For each subset, we check up to n elements to decide inclusion. So total time is O(n * 2^n).
