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

Permutations II

MediumBacktracking

You get a list of numbers, nums, that may contain the same value more than once. Return every distinct ordering of the list.

Two orderings that read the same from left to right count once, even if they came from swapping two equal numbers. The orderings can be returned in any order.

Example 1

Input:  nums = [7, 4, 4]
Output: [[4, 4, 7], [4, 7, 4], [7, 4, 4]]
Why:    the 7 can go in any of three places; the 4s fill the rest
2 more examples and the constraints

Example 2

Input:  nums = [0, -1, 2]
Output: [[-1, 0, 2], [-1, 2, 0], [0, -1, 2],
         [0, 2, -1], [2, -1, 0], [2, 0, -1]]
Why:    no repeats, so all 3! = 6 orderings are distinct

Example 3

Input:  nums = [5, 5, 5]
Output: [[5, 5, 5]]
Why:    every ordering reads the same

Constraints

  • 1 ≤ length of nums ≤ 8
  • −10 ≤ nums[i] ≤ 10

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. All orderings + a setO(n · n!)
  2. Sort and skip repeatsO(n · n!)

The idea in one sentence

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

Side by side

ApproachTimePaths built for [1, 1, 1, 1, 2, 2, 2, 2]Verdict
All orderings + a setO(n · n!)
Builds 40,320 to keep 70
Sort and skip repeatsO(n · n!)
Best; builds only the 70

n = length of nums. The worst case is the same; the difference is how many duplicates get built.

Edge cases to test

  • One number. [−10] has one ordering: [[−10]].
  • All the same. [5, 5, 5] gives a single ordering.
  • No repeats. [0, −1, 2] must give all 6 orderings; the skip rule never fires.
  • Several repeated values. [1, 1, 2, 2] has 4! / (2! · 2!) = 6 distinct orderings.

Common mistakes

  • Forgetting to sort, so equal values are not neighbours and the skip rule misses duplicates.
  • Skipping when nums[i − 1] is used instead of when it is not, which drops valid orderings like [4, 4, 7].
  • Appending path itself instead of a copy, so every result ends up as the same emptied list.

How to talk through it

  1. 1Clarify. Can values repeat? Does the order of the results matter? How long can the list be?
  2. 2Give the simple fix. Generate every ordering and deduplicate with a set; say it builds n! paths no matter what.
  3. 3Find where duplicates come from. Two equal values taking turns in the same slot. Sorting puts them side by side.
  4. 4Code the skip rule. Skip i when it equals the previous value and the previous one is not used.
  5. 5Test out loud. Run [7, 4, 4], all equal values, and a list with no repeats.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?