Coding problem · Medium · Backtracking

Permutations

Medium Algorithms & data structures Seen at Microsoft, Meta, LinkedIn

Given an array nums of distinct integers, return all possible permutations, in any order.

Example 1

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

Example 2

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

Hints

Hint 1

Build a permutation position by position, tracking which numbers are already used.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

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

Backtracking with a used set: at each depth, try every unused number, recurse, then undo. When the current permutation has all n numbers, record a copy. There are n! permutations, each built in O(n).

Reference solution

function permute(nums) {
  const out = [];
  const cur = [];
  const used = new Set();
  const go = () => {
    if (cur.length === nums.length) return void out.push([...cur]);
    for (const x of nums) {
      if (used.has(x)) continue;
      used.add(x); cur.push(x);
      go();
      cur.pop(); used.delete(x);
    }
  };
  go();
  return out;
}