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,320orderings.
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.
- 1 <= nums.length <= 8
- -10 <= nums[i] <= 10
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]withnums[i-1]not in use. Ifnums[i-1]is in use, it sits in an earlier slot, so this copy is the first one available here.
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.
Approach
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.
Two ways to avoid repeats
One used flag per index and a one-line skip test.
- Closest to plain permutations: only the skip line is new.
- Needs sorting: the test compares neighbours.
Count how many copies of each value are left, and at every slot loop over distinct values instead of indices.
- No sort, no skip rule: a value is tried once per slot because it appears once in the count map.
- Easier to argue: duplicates are impossible by construction.
Both build each distinct ordering once and cost O(n · n!). The sorted skip rule is the one traced below.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Skipping every repeated value
if i > 0 and nums[i] == nums[i - 1]:
continueif i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continueWithout 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
res = [list(p) for p in set(permutations(nums))]
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.
Edge cases
At every slot only the first free copy passes the test, so the search walks one straight path and returns a single ordering.
The skip test never fires and the output is all n! orderings, the same as plain permutations.
Complexity
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.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.