Generate Unique Lexicographical Permutations
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Enumerate all unique permutations of an integer list containing duplicates in lexicographically sorted order.
Given a list of integers that may include repeating values, return every distinct permutation of all elements in the list.
The output list must contain each unique permutation exactly once, arranged in strictly ascending lexicographical order.
Constraints
1 <= len(nums) <= 8-10 <= nums[i] <= 10- The total number of distinct permutations generated will not exceed 40,320.
Examples
Example 1
Input: distinct_permutations([1, 1, 2])
Output: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Example 2
Input: distinct_permutations([0, -1, 0])
Output: [[-1, 0, 0], [0, -1, 0], [0, 0, -1]]
Example 3
Input: distinct_permutations([7])
Output: [[7]]
Hints
Hint 1
If the input array is initially sorted, the very first permutation will naturally be the smallest lexicographical arrangement.
Hint 2
Consider how to find the next lexicographical successor directly without generating duplicates.
Hint 3
Alternatively, recursive backtracking can be used: sort the array first, and at each decision level, avoid picking equal elements more than once for the same position.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To generate all unique permutations in lexicographical order without generating duplicates or sorting a large result collection at the end, we can iteratively generate each next permutation in place.
- Sort the array initially: Sorting
numsgives us the lexicographically smallest starting sequence. - Find the rightmost pivot: Scan backward from the second to last index to find the first index $i$ such that $a[i] < a[i + 1]$. If no such index exists, the entire sequence is in non-increasing order, meaning we have generated all permutations.
- Find the successor: Scan backward from the last element to find the smallest element $a[j]$ strictly greater than $a[i]$ (i.e., the rightmost index $j$ where $a[j] > a[i]$).
- Swap and Reverse: Swap $a[i]$ and $a[j]$, then reverse the sub-array from index $i + 1$ to the end. Reversing this suffix turns it into ascending order, which produces the smallest possible suffix for the new prefix.
- Collect result: Save a copy of the transformed array into the output list and repeat the process until no further pivot can be found.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \cdot P)$, where $N$ is the length of
nums($N \le 8$) and $P$ is the total number of unique permutations ($P \le N!$). Constructing each successor takes $\mathcal{O}(N)$ time, and copying the array of length $N$ into the output list also costs $\mathcal{O}(N)$. - Space Complexity: $\mathcal{O}(N \cdot P)$ to store the output list of permutations. The auxiliary space used by the algorithm itself is $\mathcal{O}(1)$ beyond input/output structures.
Python Reference Solution
from typing import List
def distinct_permutations(nums: List[int]) -> List[List[int]]:
a = sorted(nums)
n = len(a)
result = [a[:]]
while True:
i = n - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1
if i < 0:
break
j = n - 1
while a[j] <= a[i]:
j -= 1
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:])
result.append(a[:])
return result