KatInterview

Generate Unique Lexicographical Permutations

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searcharrayssortingbacktracking

Last 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.