Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start the permutation by calling the helper function.
DSA Javascript
function permute(nums) {
const result = [];
function backtrack(path, options) {
if (options.length === 0) {
result.push(path.slice());
return;
}
for (let i = 0; i < options.length; i++) {
path.push(options[i]);
backtrack(path, options.filter((_, idx) => idx !== i));
path.pop();
}
}
[1];
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling backtrack with arguments in wrong order.
Not passing an empty array as the initial path.
✗ Incorrect
The helper function backtrack is called with an empty path and the full nums array as options to start generating permutations.
2fill in blank
mediumComplete the code to add the current path copy to the result when no options remain.
DSA Javascript
function backtrack(path, options) {
if (options.length === 0) {
result.[1](path.slice());
return;
}
for (let i = 0; i < options.length; i++) {
path.push(options[i]);
backtrack(path, options.filter((_, idx) => idx !== i));
path.pop();
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push.
Using slice or concat incorrectly.
✗ Incorrect
We use push to add a copy of the current path to the result array when no options remain.
3fill in blank
hardFix the error in the for loop condition to iterate over all options.
DSA Javascript
for (let i = 0; i < [1]; i++) { path.push(options[i]); backtrack(path, options.filter((_, idx) => idx !== i)); path.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using path.length which changes during recursion.
Using nums.length which is fixed and not filtered.
✗ Incorrect
The loop must run from 0 to options.length to cover all available options for the current step.
4fill in blank
hardFill both blanks to create a new options array excluding the current index.
DSA Javascript
backtrack(path, options.[1]((_, idx) => idx !== [2]));
Attempts:
3 left
💡 Hint
Common Mistakes
Using map which transforms elements but does not remove.
Using slice which does not exclude specific indices.
✗ Incorrect
We use filter to exclude the current index from options, so the next recursion step has one less element.
5fill in blank
hardFill all three blanks to complete the permutation function with helper and return result.
DSA Javascript
function permute([1]) { const result = []; function backtrack([2], options) { if (options.length === 0) { result.push([3]); return; } for (let i = 0; i < options.length; i++) { path.push(options[i]); backtrack(path, options.filter((_, idx) => idx !== i)); path.pop(); } } backtrack([], nums); return result; }
Attempts:
3 left
💡 Hint
Common Mistakes
Not copying path before pushing to result.
Using wrong parameter names in backtrack.
✗ Incorrect
The function permute takes nums; backtrack takes path and options; when options is empty, push a copy of path using path.slice() to result.
