Typorithm · medium

Permutations

▷ Interactive algorithm labpermutationsbacktrackingorderingsused-arraychoose-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 Permutations

0%

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.

Preparing algorithm lab…
01

Base case: path is full length.

02

Skip elements already used.

03

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

Read the implementation

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

1. Full length

A complete permutation uses every element exactly once.

if (path.length === nums.length)

2. Try every index

Order matters, so each position may use any unused element.

for (let i = 0; i < nums.length; i += 1)

3. Skip used

A used element cannot appear twice in one permutation.

if (used[i]) continue

4. Mark + choose

Mark the element used before recursing.

used[i] = true

5. Unmark (undo)

Free the element again for sibling branches.

used[i] = false

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.

Permutations: Visual Walkthrough & Practice · Typorithm | ApplyDjinn