Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the result array for storing subsets.
DSA Javascript
function subsets(nums) {
const result = [1];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using {} which creates an object instead of an array.
Using null or 0 which are not containers.
✗ Incorrect
We use an empty array [] to store all subsets generated.
2fill in blank
mediumComplete the code to start the recursive helper function call with initial parameters.
DSA Javascript
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([1], path);
path.pop();
}
}
backtrack(0, []);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing start + 1 which does not move forward correctly.
Passing 0 which causes infinite recursion.
✗ Incorrect
We move to the next index i + 1 to avoid reusing elements.
3fill in blank
hardFix the error in the recursive function to correctly copy the current path before pushing.
DSA Javascript
function subsets(nums) {
const result = [];
function backtrack(start, path) {
result.push([1]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing path directly stores a reference, causing all subsets to be the same.
Using path.concat() without arguments returns the same array.
✗ Incorrect
Using [...path] creates a new copy of the current subset to store.
4fill in blank
hardFill both blanks to create a function that generates all subsets using iteration.
DSA Javascript
function subsets(nums) {
let result = [[]];
for (const num of nums) {
const newSubsets = result[1](subset => [...subset, num]);
result = result[2]newSubsets;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using filter which only selects elements, not transforms.
Using reduce which is more complex here.
Using forEach which returns undefined.
✗ Incorrect
We use map to create new subsets and then concatenate them to result.
5fill in blank
hardFill all three blanks to create a recursive function that generates subsets with backtracking.
DSA Javascript
function subsets(nums) {
const result = [];
function backtrack([1], [2]) {
result.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, [3]);
path.pop();
}
}
backtrack(0, []);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using nums or result as parameters which are not needed.
Not passing path in recursive call causing errors.
✗ Incorrect
The function takes start and path parameters; path is passed recursively.
