Permutations

Difficulty: Medium

Given a list of distinct numbers, return every possible ordering (permutation), using each number exactly once per ordering.

Examples

Input: nums = [1, 2, 3]
Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

There are 3! = 6 ways to arrange three distinct numbers.

Input: nums = [0, 1]
Output: [[0,1], [1,0]]

Two numbers can be arranged in 2! = 2 ways.

Constraints

  • 1 <= nums.length <= 6

  • All numbers in nums are unique.

Approach

Build one arrangement a position at a time. At each position, try every number not already used in this arrangement, then fill the next position. When every position is filled, you have one permutation.

Track "used" with an array of booleans. Before placing a number, check it isn't used; after exploring what follows, mark it unused before trying the next candidate. It's the same try/explore/undo rhythm, applied to positions instead of include/exclude decisions.

A neat trick skips the tracker: keep the numbers in one array, swap each candidate further down into the current position, recurse, then swap back. Everything before the current position is locked in; everything from it onward is still available - so no separate "used" structure is needed.

Solutions

Backtracking — Track Used Numbers

Build the arrangement in an array, with a boolean array marking placed numbers. At each position, try every unused number: mark it used, place it, recurse, then remove it and unmark it.

function permute(nums) {
  const result = [];
  const current = [];
  const used = new Array(nums.length).fill(false);

  function backtrack() {
    if (current.length === nums.length) {
      result.push([...current]);
      return;
    }

    for (let i = 0; i < nums.length; i++) {
      if (used[i]) continue;

      used[i] = true;
      current.push(nums[i]);

      backtrack();

      current.pop();
      used[i] = false;
    }
  }

  backtrack();
  return result;
}

Time: O(n * n!) · Space: O(n) auxiliary (used array + recursion + current array), plus O(n * n!) output

Optimal — In-Place Swapping

Skip the "used" tracker: everything before the current position is locked in, and everything from it onward is still available. To try a candidate, swap it into place, recurse on the next position, then swap back - no extra array needed.

function permute(nums) {
  const result = [];

  function backtrack(start) {
    if (start === nums.length) {
      result.push([...nums]);
      return;
    }

    for (let i = start; i < nums.length; i++) {
      [nums[start], nums[i]] = [nums[i], nums[start]];

      backtrack(start + 1);

      [nums[start], nums[i]] = [nums[i], nums[start]]; // swap back
    }
  }

  backtrack(0);
  return result;
}

Time: O(n * n!) · Space: O(n) recursion depth only (no separate tracker), plus O(n * n!) output