Permutations II Problem
Description
LeetCode Problem 47.
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
- 1 <= nums.length <= 8
- -10 <= nums[i] <= 10
Solution
Approach: Backtracking with Sorted Duplicates
Generating every permutation and removing duplicates with a set works, but it wastes time producing the same permutation many times ([1,1,1,1,1,1,1,1] would produce 8! copies of one answer). Instead, avoid creating duplicates in the first place.
Build each permutation one position at a time, as in the problem without duplicates: path is the permutation being built and used[i] says whether nums[i] is in it. The new idea is how to treat equal numbers:
- Sort
nums, so equal numbers sit next to each other. - When choosing the next number, skip
nums[i]ifnums[i] == nums[i - 1]andnums[i - 1]is not used.
The rule in step 2 forces equal numbers to be placed in left-to-right order: the second 1 can only be chosen after the first 1 is already in path. Swapping two equal numbers gives the same permutation, so fixing their order keeps exactly one copy of each unique permutation, and it still allows every distinct arrangement.
The check is !used[i - 1], not used[i - 1]: if the earlier equal number is unused, choosing nums[i] here would produce the same branch that choosing nums[i - 1] already explored.
Complexity: O(n · n!) time in the worst case (all numbers distinct), where n is the length of nums; each unique permutation costs O(n) to copy. O(n) extra space for path, used and the recursion, not counting the output.
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort() # equal numbers become neighbours
result = []
path = [] # the permutation being built
used = [False] * len(nums) # used[i]: nums[i] is already in path
def backtrack():
if len(path) == len(nums):
result.append(path[:]) # copy, since path keeps changing
return
for i in range(len(nums)):
if used[i]:
continue
# Among equal numbers, always take them left to right: skip nums[i]
# if an equal number before it is still unused at this position.
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop() # undo the choice before trying the next number
used[i] = False
backtrack()
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.