Skip to content
DSA Patterns
Menu
Language
BacktrackingLC #462 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Permutations

Problem (restated)

Given a list of distinct integers, return all possible permutations.

Intuition

Backtracking: choose an unused number, recurse, undo. When path length == n, record a copy.

Approaches

Backtracking with used flags

Unverified
Time O(n · n!)Space O(n)

Idea. path list + used boolean array. Try each unused index, recurse, pop.

Walkthrough. [1,2,3] explores 6 permutations.

Trade-offs. Swap-based in-place generation uses less auxiliary memory for path but is harder to read.

Solution
export function permute(nums: number[]): number[][] {
  const res: number[][] = [];
  const path: number[] = [];
  const used = new Array(nums.length).fill(false);
  const dfs = () => {
    if (path.length === nums.length) { res.push([...path]); return; }
    for (let i = 0; i < nums.length; i++) {
      if (used[i]) continue;
      used[i] = true; path.push(nums[i]!);
      dfs();
      path.pop(); used[i] = false;
    }
  };
  dfs();
  return res;
}
export function permute(nums: number[]): number[][] {
  const res: number[][] = [];
  const path: number[] = [];
  const used = new Array(nums.length).fill(false);
  const dfs = () => {
    if (path.length === nums.length) { res.push([...path]); return; }
    for (let i = 0; i < nums.length; i++) {
      if (used[i]) continue;
      used[i] = true; path.push(nums[i]!);
      dfs();
      path.pop(); used[i] = false;
    }
  };
  dfs();
  return res;
}

Template connection

Permutations: a used[] flag per index. Append an unused index, recurse, then pop and clear the flag. Record the path when its length is n.

Reflection

  • used[i] skips a value you already picked. There are n! leaves. Forget to clear the flag on the way back and the next branch is missing choices.
  • Values are unique. Swapping and swapping back builds the same tree.
  • One element is one permutation. An empty array has one empty answer.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Permutations of distinct [1,2,3]. Choose unused, recurse, undo.

1
0
2
1
3
2
stack
∅

path = []

Key:CurrentActive rangeMatchSettled