Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start the recursive function for combinations.
DSA Javascript
function combineSumK(nums, k) {
const result = [];
function backtrack(start, path, sum) {
if (sum === k) {
result.push([...path]);
return;
}
for (let i = [1]; i < nums.length; i++) {
if (sum + nums[i] > k) continue;
path.push(nums[i]);
backtrack(i + 1, path, sum + nums[i]);
path.pop();
}
}
backtrack(0, [], 0);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop from 1 skips the first element.
Using sum or nums[0] as start index causes errors.
✗ Incorrect
The loop should start from 'start' to consider all elements from the current position.
2fill in blank
mediumComplete the code to check if the current sum equals the target k.
DSA Javascript
function backtrack(start, path, sum) {
if ([1] === k) {
result.push([...path]);
return;
}
// rest of code
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking path length instead of sum.
Comparing start or nums.length to k.
✗ Incorrect
We compare the current sum with k to find valid combinations.
3fill in blank
hardFix the error in the pruning condition to skip sums greater than k.
DSA Javascript
for (let i = start; i < nums.length; i++) { if ([1] + nums[i] > k) continue; path.push(nums[i]); backtrack(i + 1, path, sum + nums[i]); path.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using start or i instead of sum causes wrong pruning.
Using path length instead of sum.
✗ Incorrect
We add nums[i] to the current sum to check if it exceeds k.
4fill in blank
hardFill in the blanks to correctly call the backtrack function and remove the last element.
DSA Javascript
path.push(nums[i]); backtrack([1], path, [2]); path.[3]();
Attempts:
3 left
💡 Hint
Common Mistakes
Using push instead of pop to remove element.
Not updating sum correctly in recursive call.
✗ Incorrect
We move to the next index i+1, update sum by adding nums[i], and remove last element with pop after recursion.
5fill in blank
hardFill all three blanks to complete the function that returns all combinations summing to k.
DSA Javascript
function combineSumK(nums, k) {
const result = [];
function backtrack([1], path, [2]) {
if ([2] === k) {
result.push([...path]);
return;
}
for (let i = [1]; i < nums.length; i++) {
if ([2] + nums[i] > k) continue;
path.push(nums[i]);
backtrack(i + 1, path, [2] + nums[i]);
path.pop();
}
}
backtrack(0, [], 0);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for parameters.
Starting loop from 0 instead of 'start' inside backtrack.
✗ Incorrect
The backtrack function uses 'start' as the first parameter, 'sum' as the third parameter, and the loop starts from 'start'.
