Hint: Check bit positions for element inclusion [OK]
Common Mistakes:
Missing empty subset []
Swapping order of subsets
Ignoring bitmask 0 producing empty subset
4. Identify the error in the following code snippet for generating subsets using bitmask:
const arr = [1, 2, 3];
const subsets = [];
for (let mask = 0; mask <= (1 << arr.length); mask++) {
let subset = [];
for (let i = 0; i < arr.length; i++) {
if (mask & (1 << i)) {
subset.push(arr[i]);
}
}
subsets.push(subset);
}
console.log(subsets);
medium
A. The subsets array should be cleared inside the outer loop.
B. The inner loop should run until i <= arr.length.
C. The bitwise AND condition should be (mask | (1 << i)) instead of &.
D. The outer loop condition should be mask < (1 << arr.length), not <=.
Solution
Step 1: Check outer loop range
The outer loop runs from 0 to (1 << arr.length) inclusive, which is one too many iterations (should be less than).
Step 2: Correct loop condition
It should be mask < (1 << arr.length) to avoid an extra invalid subset iteration.
Final Answer:
The outer loop condition should be mask < (1 << arr.length), not <=. -> Option D
Quick Check:
Loop runs 2^n times, not 2^n+1 [OK]
Hint: Use <, not <=, for bitmask loop end [OK]
Common Mistakes:
Using <= instead of < in loop condition
Confusing bitwise AND (&) with OR (|)
Extending inner loop beyond array length
5. Given an array arr = [1, 2, 3, 4], how many subsets will be generated by the bitmask method, and what is the subset generated when mask = 9? (mask is in decimal)
hard
A. 16 subsets; subset for mask 9 is [1, 4]
B. 8 subsets; subset for mask 9 is [2, 3]
C. 16 subsets; subset for mask 9 is [2, 4]
D. 15 subsets; subset for mask 9 is [1, 3, 4]
Solution
Step 1: Calculate total subsets for array length 4
Total subsets = 2^4 = 16.
Step 2: Decode mask 9 in binary and map to elements
9 in binary is 1001. Bits set at positions 0 and 3 correspond to arr[0] = 1 and arr[3] = 4.
Final Answer:
16 subsets; subset for mask 9 is [1, 4] -> Option A
Quick Check:
2^4 = 16 subsets; mask 9 = 1001 binary [OK]
Hint: Convert mask to binary, map bits to elements [OK]
Common Mistakes:
Miscounting total subsets as 15
Misinterpreting binary mask bits
Confusing element indices with bit positions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.