LeetCode #47 Medium

Permutations II

Permutations II is LeetCode 47 (Medium). The array nums may contain repeated values. Return every distinct ordering of it, each exactly once, in any order.

  • Two orderings that read the same are one answer, even if they place different copies of a value.
  • At most 8 numbers, so the output has at most 8! = 40,320 orderings.

Listing permutations with duplicates in the input is the twist on Permutations: the search is the same slot-by-slot backtracking, and what is new is how it avoids building an ordering twice.

Constraints
  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10
backtrackingarraysortingrecursion
Open on LeetCode ↗
02

Intuition

A duplicate ordering is born at one level of the recursion: the same slot gets the same value twice, once from each copy, and the two branches below are mirror images. So the fix is local.

  • One try per value per slot: at each depth, once a value has been tried in this slot, skip every other copy of it.
  • Sort to make copies neighbours: then "another copy of a value already tried here" is the test nums[i] == nums[i-1] with nums[i-1] not in use. If nums[i-1] is in use, it sits in an earlier slot, so this copy is the first one available here.
How to spot this pattern

You must list arrangements where order matters, and the input can repeat values while the answer must not. Any time a backtracking search produces duplicate results, look for the level where two branches start with equal choices and cut there, instead of filtering results afterwards.

03

Approach

Try it first

Before reading on: sorted nums = [1, 1, 2]. At the first slot, the search tries the first 1. When it comes back and reaches the second 1, why must it skip it? Two levels down, the second 1 is placed after the first: why is that allowed? Target the same bound as plain permutations.

1

Sort the array first

Sorting puts every copy of a value next to each other. The skip test only compares a value with its left neighbour, so it is only correct when all equal values are adjacent.

2

Fill one slot per level

Keep path (the values placed so far) and used[i] per index. At each level scan every index, skip the used ones, and when path holds all n values record a copy of it.

3

Skip a copy whose left twin is free

Before placing nums[i], skip it if nums[i] == nums[i-1] and used[i-1] is false. The twin being free means this level's loop already tried it (it has a smaller index), so this branch would rebuild the same orderings.

4

Why every ordering still appears once

The rule forces equal values to enter path in index order: the second 1 can only be placed after the first 1 is. For any distinct ordering, exactly one assignment of copies to positions does that, so it is built once, never zero times and never twice.

5

Undo after each branch

Pop the value and clear used[i] when the call returns. The skip test reads used[i-1], so a flag left on by a finished branch would wrongly let the next twin through.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def permuteUnique(self, nums: list[int]) -> list[list[int]]:
▶3 nums.sort()
▶4 res, path = [], []
▶5 used = [False] * len(nums)
▶6 
▶7 def backtrack():
▶8 if len(path) == len(nums):
▶9 res.append(path[:])
▶10 return
▶11 for i in range(len(nums)):
▶12 if used[i]:
▶13 continue
▶14 if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
▶15 continue
▶16 used[i] = True
▶17 path.append(nums[i])
▶18 backtrack()
▶19 path.pop()
▶20 used[i] = False
▶21 
▶22 backtrack()
▶23 return res
sorted1a1b2green = in useslot 1slot 2slot 3startfoundsorted: equal values sit side by side
pathempty
in usenone
found0
Sort first. Copies of the same value are now neighbours, labelled a, b, … in index order. The skip test only compares a value with its left neighbour, so this is what makes it reliable.
sorted1a1b2green = in useslot 1slot 2slot 3start1afoundplace 1a in slot 1
path1a
in use1a
found0
Place 1a in slot 1. Value 1 has not been tried in slot 1 yet. Mark it in use and move down to slot 2.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1bfoundplace 1b: twin 1a is in use
path1a 1b
in use1a, 1b
found0
Place 1b in slot 2. 1b equals 1a, but 1a is already on the path in an earlier slot, so this is the first time value 1 is tried in slot 2. Allowed. Mark it in use and move down to slot 3.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b2found112path full: record 1 1 2
path1a 1b 2
in use1a, 1b, 2
found1
Place 2 in slot 3. Value 2 has not been tried in slot 3 yet. Every slot is filled, so record a copy of the path: ordering number 1.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b2found112undo: take back 2 and 1b
path1a
in use1a
found1
Back up. Everything below has been tried, so take 2 and then 1b back off the path and mark them free again. Slot 2 tries its next value.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b22found112place 2 in slot 2
path1a 2
in use1a, 2
found1
Place 2 in slot 2. Value 2 has not been tried in slot 2 yet. Mark it in use and move down to slot 3.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221bfound112121path full: record 1 2 1
path1a 2 1b
in use1a, 1b, 2
found2
Place 1b in slot 3. 1b equals 1a, but 1a is already on the path in an earlier slot, so this is the first time value 1 is tried in slot 3. Allowed. Every slot is filled, so record a copy of the path: ordering number 2.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221bfound112121undo: take back 1b and 2 and 1a
pathempty
in usenone
found2
Back up. Everything below has been tried, so take 1b and then 2 and then 1a back off the path and mark them free again. Slot 1 now looks at its next candidate.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1bfound1121211b skipped: twin 1a is free
pathempty
in usenone
found2
Same value, same slot. 1b equals 1a, and 1a is not on the path, which means slot 1 already tried value 1 through 1a. Everything under 1b here would repeat that branch, so it is cut before it starts.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b2found112121place 2 in slot 1
path2
in use2
found2
Place 2 in slot 1. Value 2 has not been tried in slot 1 yet. Mark it in use and move down to slot 2.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b21afound112121place 1a in slot 2
path2 1a
in use1a, 2
found2
Place 1a in slot 2. Value 1 has not been tried in slot 2 yet. Mark it in use and move down to slot 3.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b21a1bfound112121211path full: record 2 1 1
path2 1a 1b
in use1a, 1b, 2
found3
Place 1b in slot 3. 1b equals 1a, but 1a is already on the path in an earlier slot, so this is the first time value 1 is tried in slot 3. Allowed. Every slot is filled, so record a copy of the path: ordering number 3.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b21a1bfound112121211undo: take back 1b and 1a
path2
in use2
found3
Back up. Everything below has been tried, so take 1b and then 1a back off the path and mark them free again. Slot 2 now looks at its next candidate.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b21a1b1bfound1121212111b skipped: twin 1a is free
path2
in use2
found3
Same value, same slot. 1b equals 1a, and 1a is not on the path, which means slot 2 already tried value 1 through 1a. Everything under 1b here would repeat that branch, so it is cut before it starts.
sorted1a1b2green = in useslot 1slot 2slot 3start1a1b221b1b21a1b1bfound1121212113 unique orderings, none repeated
pathempty
in usenone
found3
Done: 3 orderings. Without the skip rule the search would have built 6 paths, 3 of them repeats. Each red branch was cut at the slot where the repeat would have started.
05

Count each distinct value

Each slot loops over the distinct values that still have copies left. Taking a value lowers its count, and the count goes back up when the branch returns. Equal copies are never told apart, so no ordering can be built twice.

▶1class Solution:
▶2 def permuteUnique(self, nums: list[int]) -> list[list[int]]:
▶3 left = Counter(nums)
▶4 res, path = [], []
▶5 
▶6 def backtrack():
▶7 if len(path) == len(nums):
▶8 res.append(path[:])
▶9 return
▶10 for v in left:
▶11 if left[v] == 0:
▶12 continue
▶13 left[v] -= 1
▶14 path.append(v)
▶15 backtrack()
▶16 path.pop()
▶17 left[v] += 1
▶18 
▶19 backtrack()
▶20 return res
06

Common pitfalls

Skipping every repeated value

✗ Wrong
if i > 0 and nums[i] == nums[i - 1]:
    continue
✓ Right
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
    continue

Without the used check, the second copy can never be placed, even in a later slot after the first copy. For [1, 1, 2] no path ever reaches length 3, so the result is [].

Removing duplicates from the finished list

✗ Wrong
res = [list(p) for p in set(permutations(nums))]
✓ Right
Cut the repeated branch at the slot where it starts.

The search still builds all n! orderings. For [1,1,1,1,1,1,1,1] that is 40,320 identical orderings built and hashed to keep one; the skip rule builds that one ordering and nothing else.

07

Edge cases

All values equal

At every slot only the first free copy passes the test, so the search walks one straight path and returns a single ordering.

No repeated values

The skip test never fires and the output is all n! orderings, the same as plain permutations.

08

Complexity

Time
O(n · n!)
Space
O(n)
The number of distinct orderings is n! / (c1! · c2! · …), where c1, c2, … count each value, and writing one out takes n numbers. Skipped twins are cut at once, so the search does work proportional to that output, up to n! when nothing repeats. Extra space is path, used and the recursion depth, not counting the output.
09

Permutations II FAQ

How many unique permutations does an array with repeats have?

n! divided by the factorial of each value's count. [1, 1, 2] has 3! / 2! = 3; [1, 1, 2, 2] has 4! / (2! · 2!) = 6. Swapping two equal values gives the same ordering, which is why each group of c equal values divides the total by c!.

Does the test also work with used[i - 1] instead of not used[i - 1]?

Yes, it still returns each ordering once: it forces equal values into reverse index order instead. But it only cuts a repeat deep in the tree, after the branch has already been entered, so it explores many more dead paths. The not used version cuts at the top of the repeated branch.

Can I use the swap method from plain permutations here?

Yes, with a set per level: at slot k, before swapping nums[j] into position k, skip it if that value was already swapped in at this slot. Sorting alone is not enough there, because the swaps reorder the tail and break the neighbour order the skip test needs.