Given a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
Input: [1,1,2]
Output: [[1,1,2], [1,2,1], [2,1,1]]
To generate unique permutations for an array that might contain duplicates, we can use the following strategy:
Sort the Array: Start by sorting the array. Sorting helps in easily skipping duplicates.
Use Backtracking with a Visited Array: Use a backtracking approach with a visited
array to keep track of the elements that have been included in the current permutation.
Here’s the Python code to solve the problem:
def permuteUnique(nums):
def backtrack(path, visited):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if visited[i]:
continue
if i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]:
continue
visited[i] = True
path.append(nums[i])
backtrack(path, visited)
path.pop()
visited[i] = False
nums.sort()
result = []
visited = [False] * len(nums)
backtrack([], visited)
return result
Sorting nums
: The nums.sort()
call sorts the input list to make it easier to handle duplicates.
backtrack
function is used to generate permutations.
path
is the current permutation being built.visited
is a list to keep track of which elements have been included in path
.Base Case: If len(path)
equals len(nums)
, append a copy of path
to result
.
nums
using index i
.
path
(checked using visited
).nums[i] == nums[i - 1]
and the previous element has not been used in this current state, skip it.path
, and continue recursively.path
and marking it as not visited.The time complexity is O(N * N!)
where N
is the length of the input list. This is because there are N!
permutations and it takes O(N)
time to copy each permutation to the result list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?