#47
Permutations II
MediumArrayBacktrackingSortingBacktrackingSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n!) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n!)Space O(n)
The optimal solution uses backtracking to generate permutations while avoiding duplicates by skipping over duplicate elements. This is more efficient than generating all permutations and filtering them later.
⚙️
Algorithm
3 steps- 1Step 1: Sort the input array to group duplicates together.
- 2Step 2: Use a backtracking function to build permutations, skipping over duplicate elements to avoid generating the same permutation multiple times.
- 3Step 3: Store each valid permutation in the result list.
solution.py15 lines
1def permuteUnique(nums):
2 def backtrack(start):
3 if start == len(nums):
4 result.append(nums[:])
5 return
6 for i in range(start, len(nums)):
7 if i > start and nums[i] == nums[start]: continue
8 nums[start], nums[i] = nums[i], nums[start]
9 backtrack(start + 1)
10 nums[start], nums[i] = nums[i], nums[start]
11
12 nums.sort()
13 result = []
14 backtrack(0)
15 return resultℹ
Complexity note: The time complexity remains O(n!) due to the generation of permutations, but we avoid unnecessary duplicates, making it more efficient in practice. The space complexity is O(n) for storing the permutations.
- 1Sorting the array helps to easily identify and skip duplicates.
- 2Backtracking allows us to build permutations incrementally and efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.