Skip to content
Problem 46 · LeetCode 46(opens in a new tab)

Permutations

MediumArrays

You are given nums, a list of distinct whole numbers. A permutation is the same numbers written in some order, each number used exactly once.

Return every permutation of nums. The list of permutations may be in any order, but each permutation must appear exactly once.

Example 1

Input:  nums = [2, 5, 8]
Output: [[2,5,8], [2,8,5], [5,2,8],
         [5,8,2], [8,2,5], [8,5,2]]
Why:    3 choices for the first spot, 2 for the next, 1 left: 6 orders
2 more examples and the constraints

Example 2

Input:  nums = [-1, 4]
Output: [[-1,4], [4,-1]]
Why:    either number can go first

Example 3

Input:  nums = [9]
Output: [[9]]
Why:    one number has a single order

Constraints

  • 1 ≤ length of nums ≤ 6
  • −10 ≤ nums[i] ≤ 10
  • No number appears twice in nums

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Insert into every slotO(n · n!)
  2. Backtracking with used marksO(n · n!)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 6 numbersVerdict
Insert into every slotO(n · n!)
Passes; copies a lot
Backtracking with used marksO(n · n!)
Best; the standard answer

n = length of nums. n! is the number of permutations, so every method is at least O(n · n!).

Edge cases to test

  • One number. [9] gives [[9]]: one ordering, not an empty list.
  • Negative numbers and zero. Values are only placed, never added, so −10 and 0 behave like any other number.
  • The largest input. Six numbers give 720 permutations of length 6. Small, but they must all be distinct.
  • Copying the path. Appending path itself instead of a copy leaves the result full of empty lists after the undo steps.

Common mistakes

  • Adding the path to the result without copying it, so later pops change the stored answers.
  • Forgetting to clear the used mark after the recursive call, so later branches skip numbers they need.
  • Checking whether a value is already in the path with a linear scan instead of a used mark, which works but costs O(n) per check.

How to talk through it

  1. 1Clarify. Are the numbers distinct? Does the order of the output matter? How large can the list get?
  2. 2Count the output. There are n! orderings of length n, so O(n · n!) is the floor; say so before you code.
  3. 3Describe the search. Fill one slot at a time with an unused number. Full path: record it. Then undo and try the next.
  4. 4Code the backtracking. Mark, push, recurse, pop, unmark. Copy the path when you record it.
  5. 5Test out loud. Run [9] and [-1, 4] by hand, and check that [2, 5, 8] gives 6 lists.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?