Permutations II (LeetCode 47): Solution and Explanation
Given an array nums of up to 8 integers that may repeat, return every distinct permutation exactly once, in any order.
Intuition
Plain permutation backtracking fills one slot at a time with any tile that is not already in the path. With [1,1,2] that produces 6 orderings, but swapping the two 1s does not change the sequence, so half of them are copies.
A copy is born at one specific moment: when two equal tiles are both offered for the same slot at the same depth. Whichever of them you pick, the rest of the search below is identical, so the second pick can only rebuild what the first already built.
Sorting puts equal values next to each other, which lets us tell the copies apart by index. Now add one rule: a copy may be placed only if its left twin is already in the path. If the left twin is unused, it has already been tried in this slot, so skip.
The effect is that equal values always enter the path in left to right order. Every distinct sequence corresponds to exactly one such order, so each one is generated once, with no hash set of results needed.
Approach: Sort, then backtrack with a twin-skip rule
- Sort
numsso equal values are adjacent. - Keep a
pathand ausedarray, both empty and all false at first. - If
pathhasnvalues, copy it into the result and return. - Otherwise loop
iover every index. Skipiifused[i]is true. - Also skip
iifi > 0,nums[i] == nums[i - 1]andused[i - 1]is false. The left twin already tried this value in this slot. - Otherwise mark
used[i], pushnums[i], recurse, then pop and unmark to try the next tile.
Step-by-step example
nums = [1,1,2]
- Sorting leaves
[1,1,2]. Call the tiles 1a, 1b and 2. - Slot 1 takes 1a. Slot 2 skips 1a (used) and takes 1b, since its twin 1a is in the path. Slot 3 takes 2: record
[1,1,2]. - Back out of slot 3 and slot 2. Slot 2 now tries 2, and slot 3 takes 1b: record
[1,2,1]. - Back out to slot 1 and free 1a. Slot 1 now looks at 1b, but its twin 1a is unused, so placing 1b here would repeat the 1a branch. Skip it.
- Slot 1 takes 2. Slot 2 takes 1a, then slot 3 takes 1b: record
[2,1,1]. Inside, 1b was again skipped at slot 2 because 1a was free. - The search ends with 3 permutations:
[[1,1,2],[1,2,1],[2,1,1]].
Code: Python, Java, C++
1class Solution:
2 def permuteUnique(self, nums: List[int]) -> List[List[int]]:
3 nums.sort()
4 res = []
5 path = []
6 used = [False] * len(nums)
7
8 def backtrack():
9 if len(path) == len(nums):
10 res.append(path[:])
11 return
12 for i in range(len(nums)):
13 if used[i]:
14 continue
15 if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
16 continue
17 used[i] = True
18 path.append(nums[i])
19 backtrack()
20 path.pop()
21 used[i] = False
22
23 backtrack()
24 return res1class Solution {
2 public List<List<Integer>> permuteUnique(int[] nums) {
3 Arrays.sort(nums);
4 List<List<Integer>> res = new ArrayList<>();
5 List<Integer> path = new ArrayList<>();
6 boolean[] used = new boolean[nums.length];
7 backtrack(nums, used, path, res);
8 return res;
9 }
10
11 private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
12 if (path.size() == nums.length) {
13 res.add(new ArrayList<>(path));
14 return;
15 }
16 for (int i = 0; i < nums.length; i++) {
17 if (used[i]) continue;
18 if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
19 used[i] = true;
20 path.add(nums[i]);
21 backtrack(nums, used, path, res);
22 path.remove(path.size() - 1);
23 used[i] = false;
24 }
25 }
26}1class Solution {
2public:
3 vector<vector<int>> permuteUnique(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 vector<vector<int>> res;
6 vector<int> path;
7 vector<bool> used(nums.size(), false);
8 backtrack(nums, used, path, res);
9 return res;
10 }
11
12private:
13 void backtrack(vector<int>& nums, vector<bool>& used, vector<int>& path, vector<vector<int>>& res) {
14 if (path.size() == nums.size()) {
15 res.push_back(path);
16 return;
17 }
18 for (int i = 0; i < (int)nums.size(); i++) {
19 if (used[i]) continue;
20 if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
21 used[i] = true;
22 path.push_back(nums[i]);
23 backtrack(nums, used, path, res);
24 path.pop_back();
25 used[i] = false;
26 }
27 }
28};Time and space complexity
O(n * n!)
In the worst case all values are distinct and there are n! permutations, each copied in O(n). Duplicates only shrink the tree.
O(n)
The recursion depth, the path and the used array are all size n. The output itself is not counted.
Other approaches
Generate all, deduplicate with a set (time O(n * n!), space O(n * n!))
Run the plain permutation search and store each result as a tuple in a hash set. It is correct but explores every duplicate branch and pays memory for the set.
Counter-based backtracking (time O(n * n!), space O(n))
Count each distinct value, then fill slots by choosing a value with a positive count. Equal values are never offered twice in one slot, so no skip rule is needed.
Next permutation in a loop (time O(n * n!), space O(1))
Sort, then repeatedly apply the next-permutation step until the sequence wraps around. Next permutation naturally skips equal arrangements, so each distinct one appears once.
Common mistakes
- Forgetting to sort. The twin rule only compares neighbors, so equal values must be adjacent.
- Using
used[i - 1]instead ofnot used[i - 1]. Both versions give correct output, butnot usedprunes at the highest level and is the one that is easy to explain. Mixing them up while reasoning leads to wrong proofs. - Appending
pathitself instead of a copy, so every stored result is the same list that later gets emptied. - Not resetting
used[i]after the recursive call, which hides tiles from later branches.
Frequently asked questions
Why does the rule check that the left twin is unused?
If the left twin is unused at this slot, it was already tried here earlier in the same loop and its whole subtree is done. Placing the right twin now would build the same subtree again. If the left twin is used, it sits in an earlier slot, and placing the right twin here is a new arrangement.
Does used[i - 1] (without not) also work?
Yes, it forces equal copies into right to left order instead, which is also unique. It prunes later in the tree, though, so it explores more dead branches before giving up.
How many permutations can there be?
With 8 distinct values there are 8! = 40,320. With repeats, divide by the factorial of each value's count, for example 8 values made of four 1s and four 2s give 70.
Is a set of results ever needed?
No. With the array sorted and the twin rule in place, each distinct permutation is produced exactly once.