Permutations II solution explained
Permutations II asks for every distinct ordering of a list that may contain repeated values. The cleanest fix is to choose by value rather than by position: count each value, and at every position try each distinct value that still has copies left. The other standard fix sorts the list and skips a copy of a value whenever the copy just before it is unused, which forces equal values to be placed in a fixed order. Either way, each distinct ordering is built once.
By Evin JohnPublished 7 min read
The problem, in plain terms
Given a list of integers that may repeat, return every ordering of the whole list, without listing the same ordering twice. An ordering is identified by the sequence of values, so swapping two equal values does not make a new answer. The output order is usually up to you.
list: 5 2 5 2
distinct orderings (6):
2 2 5 5 2 5 2 5 2 5 5 2
5 2 2 5 5 2 5 2 5 5 2 2
check: 4! / (2! × 2!) = 24 / 4 = 6
by position there are 24 orderings, each answer made 4 timesThe formula in the example is worth stating early in an interview. With n values where one value appears a times, another b times and so on, the count is n! / (a! × b! × ...). It tells you how big the output is, and it is the check you run on your own result.
Brute force: all n! orderings into a set
Generate every ordering of positions, turn each into a tuple of values, and store it in a set. In Python that is one line with itertools.permutations. The problem is wasted work: a list of eight copies of one value has 40,320 position orderings and exactly one answer. The interviewer will ask how to avoid building the duplicates in the first place.
Approach 1: choose by value with a count map
Duplicates appear because the search treats the two 5s as different objects. So stop tracking positions. Count how many copies of each value remain, and at each position loop over the distinct values that still have a copy. Take one, recurse, put it back. Since every value is offered once per position, two branches can never produce the same sequence. This version needs no sorting and no skip rule, which makes it easy to defend.
from collections import Counter
def unique_permutations(nums):
left = Counter(nums)
out, pick = [], []
def go():
if len(pick) == len(nums):
out.append(pick[:])
return
for value in left: # each distinct value once per position
if left[value] == 0:
continue
left[value] -= 1
pick.append(value)
go()
pick.pop()
left[value] += 1
go()
return outChanging a Counter's counts while looping over it is safe here because no keys are added or removed during the loop, only their values change. If you ever delete a key when its count hits zero, the loop breaks, so keep the zero and skip it as the code does.
Approach 2: sort, a used array, and the skip rule
This is the version most people learn from the distinct-values problem. Sort so equal values are neighbors, keep a used flag per position, and at each depth try every unused position. Then add one rule: skip position i if it holds the same value as position i - 1 and position i - 1 is not currently used. The effect is that copies of a value can only be placed in left-to-right order. The second 5 is allowed only after the first 5 has been placed, so each distinct sequence corresponds to exactly one way of assigning the copies.
function uniquePermutations(nums) {
const sorted = nums.slice().sort((a, b) => a - b);
const used = new Array(sorted.length).fill(false);
const out = [], pick = [];
function go() {
if (pick.length === sorted.length) { out.push(pick.slice()); return; }
for (let i = 0; i < sorted.length; i++) {
if (used[i]) continue;
// equal values must be placed left to right: copy i only after copy i - 1
if (i > 0 && sorted[i] === sorted[i - 1] && !used[i - 1]) continue;
used[i] = true;
pick.push(sorted[i]);
go();
pick.pop();
used[i] = false;
}
}
go();
return out;
}Why !used[i - 1] and not used[i - 1]
Both conditions produce the right answers. The version with used[i - 1] (skip when the previous copy is in use) forces copies to be placed right to left instead, but it only discovers that a branch is hopeless deep in the tree, after placing other values. The !used[i - 1] version cuts those branches at the first level they appear. We counted recursive calls for both on a few inputs:
| Input | Answers | Calls with !used[i - 1] | Calls with used[i - 1] |
|---|---|---|---|
| 1 1 2 | 3 | 9 | 12 |
| 1 1 1 2 2 | 10 | 34 | 99 |
| eight 1s | 1 | 9 | 2,781 |
| 1 1 2 2 3 3 4 4 | 2,520 | 7,365 | 16,201 |
The count-map version from Approach 1 made the same number of calls as !used[i - 1] on all four inputs, which fits: both explore exactly the tree of distinct prefixes. If an interviewer asks which skip form to use, say !used[i - 1] and explain the left-to-right ordering.
An iterative alternative
You can also start from the sorted list and repeatedly step to the next ordering in lexicographic order (find the rightmost ascent, swap with the smallest larger value to its right, reverse the tail) until the list is in descending order. That algorithm naturally skips equal orderings, uses O(1) extra space beyond the output, and lists answers in sorted order. It is a good follow-up if the interviewer asks for answers one at a time.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| All n! orderings into a set | O(n! × n) | O(P × n) for the set |
| Count map | O(P × n × d) at most, d distinct values per loop | O(n + d), plus the output |
| Sorted, used array, !used[i - 1] | O(P × n²) at most, each node loops over n positions | O(n), plus the output |
| Next ordering, repeated | O(P × n) | O(1) beyond the output |
These bounds are loose upper limits. In the worst case all values are distinct, P is n!, and every method is factorial. Writing each answer into the output already costs P × n, so no method can beat that.
Edge cases to test
- An empty list: one answer, the empty ordering.
- One value repeated n times: exactly one answer.
- All values distinct: n! answers, the plain permutations problem.
- Negative numbers and zero, to make sure the sort is numeric where it matters.
- Two values repeated in equal numbers, such as 5 2 5 2, where the count formula is easy to check by hand.
Common mistakes
- Applying the skip rule without sorting, so equal values are not neighbors and the rule never fires.
- Skipping on sorted[i] === sorted[i - 1] alone, without checking used[i - 1]. Then the second copy can never be placed at all, and any list with a repeat returns nothing.
- Deleting a Counter key when its count reaches zero in the middle of the loop over that Counter.
- Storing pick instead of a copy, so the output fills with references to one emptied list.
- Claiming the solution is faster than factorial in the worst case. It is not, since the answer itself can be n! long.
How to explain it out loud
Fictional example
- Candidate
- The duplicates come from treating the two 5s as different. So I'll stop choosing positions and choose values: a map from value to copies left.
- Candidate
- At each position I try each value that still has a copy, once. Two branches start with different values, so they can't build the same sequence.
- Candidate
- The output size is n factorial over the product of each count's factorial, so that's my lower bound and my test. With 5 2 5 2 I expect six.
Related problems
The same sort-and-skip idea, applied to groups instead of orderings, appears in Subsets II and, with a target, in Combination Sum II. The count map is the same tool that solves First Unique Character in a String. For backtracking where constraints, not duplicates, prune the tree, see Sudoku Solver.
Natively during permutation drills
This problem rewards explaining why a rule works, not only writing it. When you practice, Natively on Mac or Windows can read the problem from a screenshot and produce a second approach, code included, to compare with yours. The session transcript lets you hear whether your skip-rule explanation was clear. Read more about how AI helps in coding interview prep.
Questions people ask
How do you solve Permutations II?
Count each value, then backtrack by trying each distinct value that still has copies at every position. Alternatively, sort, keep a used array, and skip position i when it equals position i - 1 and position i - 1 is unused.
Why is the condition !used[i - 1] in Permutations II?
It forces copies of a value to be placed in left-to-right order, so each distinct ordering is built once. The used[i - 1] form is also correct but explores many more dead branches.
How many unique permutations are there with duplicates?
n! divided by the factorial of each value's count. For 5, 2, 5, 2 that is 24 / (2 × 2) = 6.
What is the time complexity of Permutations II?
Factorial in the worst case, since all-distinct input has n! answers and writing them costs n! × n. With many repeats the cost tracks the number of distinct orderings instead.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
