1. Full length
A complete permutation uses every element exactly once.
if (path.length === nums.length)Typorithm · medium
Step 1 of 8 · intro card
Backtracking
Build every ordering by trying each unused element at each position, marking and unmarking as you go.
Unlike subsets, order matters and every permutation uses all n elements.
A used array tracks which elements are already in the current path so none repeats.
Mark before recursing and unmark after — the choose/explore/undo shape extended with a used set.
Base case: path is full length.
Skip elements already used.
Mark, recurse, then unmark.
function permute(nums) {
const result = [];
function backtrack(path, used) {
if (path.length === nums.length) {
result.push([...path]);
return;
}
for (let i = 0; i < nums.length; i += 1) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
backtrack(path, used);
path.pop();
used[i] = false;
}
}
backtrack([], []);
return result;
}Connect each part of the code to the concept before you type.
A complete permutation uses every element exactly once.
if (path.length === nums.length)Order matters, so each position may use any unused element.
for (let i = 0; i < nums.length; i += 1)A used element cannot appear twice in one permutation.
if (used[i]) continueMark the element used before recursing.
used[i] = trueFree the element again for sibling branches.
used[i] = falseRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputValues 1,2,3
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
Current choice path0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state