Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the outer loop for bitmask subsets generation.
DSA Javascript
for (let mask = 0; mask [1] (1 << nums.length); mask++) { // generate subset }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= instead of < causes one extra iteration.
Using > or >= causes the loop to never run.
✗ Incorrect
The loop runs from 0 to 2^n - 1, so mask must be less than 1 << nums.length.
2fill in blank
mediumComplete the inner loop to check if the j-th bit is set in the mask.
DSA Javascript
for (let j = 0; j < nums.length; j++) { if (mask & ([1])) { subset.push(nums[j]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using j << 1 shifts j instead of 1, which is incorrect.
Using right shift operators does not check the correct bit.
✗ Incorrect
To check if the j-th bit is set, use (1 << j) and bitwise AND with mask.
3fill in blank
hardFix the error in the code to correctly generate all subsets using bitmask.
DSA Javascript
function subsets(nums) {
const result = [];
for (let mask = 0; mask [1] (1 << nums.length); mask++) {
const subset = [];
for (let j = 0; j < nums.length; j++) {
if (mask & (1 << j)) {
subset.push(nums[j]);
}
}
result.push(subset);
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes an extra empty subset at the end.
Using > or >= causes the loop to skip all iterations.
✗ Incorrect
The outer loop must run while mask is less than 2^n, so use < not <=.
4fill in blank
hardFill both blanks to create a function that returns subsets of nums using bitmask.
DSA Javascript
function subsets(nums) {
const result = [];
for (let mask = 0; mask [1] (1 << nums.length); mask++) {
const subset = [];
for (let j = 0; j [2] nums.length; j++) {
if (mask & (1 << j)) {
subset.push(nums[j]);
}
}
result.push(subset);
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes loops to run one extra time leading to errors.
Using > or >= causes loops to skip iterations.
✗ Incorrect
Both loops should use < to iterate correctly over the range without extra iterations.
5fill in blank
hardFill all three blanks to generate subsets and print them.
DSA Javascript
function subsets(nums) {
const result = [];
for (let mask = 0; mask [1] (1 << nums.length); mask++) {
const subset = [];
for (let j = 0; j [2] nums.length; j++) {
if (mask & ([3])) {
subset.push(nums[j]);
}
}
result.push(subset);
}
return result;
}
const nums = [1, 2, 3];
console.log(subsets(nums));Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes off-by-one errors.
Using j << 1 does not correctly check the bit.
✗ Incorrect
Use < for loops and (1 << j) to check the j-th bit in mask.
