Typorithm · medium

Combinations

▷ Interactive algorithm labcombinationsbacktrackingn-choose-kstart-indexchoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Combinations

0%

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.

Preparing algorithm lab…
01

Base case: path length equals k.

02

Recurse from i + 1 to stay increasing.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Size k reached

A combination is complete once it holds k elements.

if (path.length === k)

2. Candidates from start

Start at the next number to keep combinations increasing and unique.

for (let i = start; i <= n; i += 1)

3. Choose i

Add the current number to the combination.

path.push(i)

4. Explore next

Recurse from i + 1 so each number is used once and order is fixed.

backtrack(i + 1, path)

5. Undo

Remove the number to try the next candidate.

path.pop()

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Combinations: Visual Walkthrough & Practice · Typorithm | ApplyDjinn