Permutations

35 min · permute()

Three speakers can take the stage in six different orders. Add one more speaker and the schedule suddenly has twenty-four possibilities.

nums holds distinct integers. Produce every permutation — every ordering that uses each input value exactly once.

Keep these rules in view:

  • Every inner array must contain all values from nums, with no omissions or repeats.
  • Order inside a permutation is the answer: [1, 2] and [2, 1] are different.
  • Return each permutation exactly once. The outer list may be in any order.

Constraints

  • 1 <= nums.length <= 7
  • -100 <= nums[i] <= 100
  • All values in nums are distinct.

Hints

Build from a smaller answer

If you already have every ordering of n - 1 values, insert the last value at every possible position in each one.

Think in positions

A growing permutation needs one value next. Try every input value that hasn't already been used on the current path.

Restore both pieces of state

After recursion returns, remove the last value and mark it unused again. Forgetting either undo leaks one branch's choice into the next branch.

Follow-up

How would your search change if nums could contain duplicate values but the returned permutations still had to be unique?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  2,
  3
]
Expected
[
  [
    1,
    2,
    3
  ],
  [
    1,
    3,
    2
  ],
  [
    2,
    1,
    3
  ],
  [
    2,
    3,
    1
  ],
  [
    3,
    1,
    2
  ],
  [
    3,
    2,
    1
  ]
]
Why
each of the three values can lead, followed by either order of the other two

Example 2

ready
Input
nums = [
  4
]
Expected
[
  [
    4
  ]
]
Why
a single value has exactly one ordering

Example 3

ready
Input
nums = [
  -1,
  2
]
Expected
[
  [
    -1,
    2
  ],
  [
    2,
    -1
  ]
]
Why
two distinct values can appear in either order

Interview signal

Asked at

AmazonMetaGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite