Challenge - 5 Problems
Powerset Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of powerset generation with duplicates
What is the output of the following JavaScript code that generates all subsets (powerset) of the array [1, 2, 2]?
DSA Javascript
function subsets(nums) {
const result = [];
nums.sort();
function backtrack(start, path) {
result.push([...path]);
for (let i = start; i < nums.length; i++) {
if (i > start && nums[i] === nums[i - 1]) continue;
path.push(nums[i]);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}
console.log(subsets([1, 2, 2]));Attempts:
2 left
💡 Hint
Duplicates are skipped to avoid repeated subsets. The subsets are generated in sorted order.
✗ Incorrect
The code sorts the input array and skips duplicates during recursion to avoid repeated subsets. The output is all unique subsets in sorted order.
❓ Predict Output
intermediateOutput of iterative powerset generation
What is the output of this iterative JavaScript code that generates all subsets of [1, 3]?
DSA Javascript
function subsets(nums) {
let result = [[]];
for (const num of nums) {
const newSubsets = [];
for (const subset of result) {
newSubsets.push([...subset, num]);
}
result = result.concat(newSubsets);
}
return result;
}
console.log(subsets([1, 3]));Attempts:
2 left
💡 Hint
The code adds each number to all existing subsets to create new subsets.
✗ Incorrect
The iterative method starts with an empty subset and adds each number to all existing subsets, doubling the count each time.
🧠 Conceptual
advancedNumber of subsets in powerset
Given an input array of length n, how many subsets does its powerset contain?
Attempts:
2 left
💡 Hint
Each element can either be included or excluded in a subset.
✗ Incorrect
Each element has two choices: to be in or out of a subset. So total subsets = 2^n.
🔧 Debug
advancedIdentify the error in recursive powerset code
What error does this code produce when generating subsets of [1, 2]?
function subsets(nums) {
const result = [];
function backtrack(start, path) {
result.push(path);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}
console.log(subsets([1, 2]));
Attempts:
2 left
💡 Hint
Look at how arrays are pushed into result and whether they are copied.
✗ Incorrect
The code pushes the same array reference 'path' multiple times without copying it, so all entries in result point to the same array which changes over time.
🚀 Application
expertFind subsets summing to target
Given the array [2, 3, 5, 7] and target sum 10, which subsets from the powerset sum exactly to 10?
Attempts:
2 left
💡 Hint
Check sums of all subsets carefully.
✗ Incorrect
Subsets [3,7] and [2,3,5] both sum to 10. Others do not.
