1. Size k reached
A combination is complete once it holds k elements.
if (path.length === k)Typorithm · medium
Step 1 of 8 · intro card
Backtracking
Pick k of n numbers by extending an increasing path, recursing from the next index each time.
Combinations are unordered selections of size k, so [1,2] and [2,1] are the same.
Forcing the path to increase (recurse from i + 1) makes each combination appear exactly once.
Stop and record once the path reaches length k.
Base case: path length equals k.
Recurse from i + 1 to stay increasing.
Choose, explore, undo.
function combine(n, k) {
const result = [];
function backtrack(start, path) {
if (path.length === k) {
result.push([...path]);
return;
}
for (let i = start; i <= n; i += 1) {
path.push(i);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(1, []);
return result;
}Connect each part of the code to the concept before you type.
A combination is complete once it holds k elements.
if (path.length === k)Start at the next number to keep combinations increasing and unique.
for (let i = start; i <= n; i += 1)Add the current number to the combination.
path.push(i)Recurse from i + 1 so each number is used once and order is fixed.
backtrack(i + 1, path)Remove the number to try the next candidate.
path.pop()Read 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 · choose 2
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