Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start the backtracking recursion from index 0.
DSA Javascript
function backtrack(nums, index) {
if (index === nums.length) {
return;
}
// process current index
backtrack(nums, [1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using index - 1 causes infinite recursion backwards.
Using 0 resets the index causing repeated calls.
Using nums.length skips all elements.
✗ Incorrect
We move forward by increasing the index by 1 to explore the next element.
2fill in blank
mediumComplete the code to add the current path to results when base case is reached.
DSA Javascript
function backtrack(nums, index, path, results) {
if (index === nums.length) {
results.push([1]);
return;
}
// continue backtracking
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing path directly causes all results to change together.
Pushing nums or index is incorrect for storing the path.
✗ Incorrect
We push a copy of path using slice() to avoid reference issues.
3fill in blank
hardFix the error in the backtracking step to correctly add and remove elements.
DSA Javascript
function backtrack(nums, index, path, results) {
if (index === nums.length) {
results.push(path.slice());
return;
}
path.push(nums[index]);
backtrack(nums, index + 1, path, results);
path.[1]();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using shift() removes wrong element.
Using push() again adds extra elements.
Using splice() without correct indices causes errors.
✗ Incorrect
We use pop() to remove the last added element to backtrack correctly.
4fill in blank
hardFill both blanks to generate all subsets of nums using backtracking.
DSA Javascript
function subsets(nums) {
const results = [];
function backtrack(start, path) {
results.push(path.slice());
for (let i = [1]; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i [2] 1, path);
path.pop();
}
}
backtrack(0, []);
return results;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 1 misses the first element.
Using '-' moves backward causing infinite loops.
✗ Incorrect
Start from start and move forward by adding 1 to i to explore subsets.
5fill in blank
hardFill all three blanks to implement backtracking for combination sum problem.
DSA Javascript
function combinationSum(candidates, target) {
const results = [];
function backtrack(start, path, total) {
if (total === [1]) {
results.push(path.slice());
return;
}
if (total > target) {
return;
}
for (let i = start; i < candidates.length; i++) {
path.push(candidates[i]);
backtrack(i, path, total [2] candidates[i]);
path.pop();
}
}
backtrack(0, [], [3]);
return results;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' causes wrong totals.
Starting total at target or other values causes logic errors.
✗ Incorrect
We check if total equals target, add candidates[i] to total, and start total at 0.
