DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Permutations II

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:

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        ctr = {}
        for num in nums:
            ctr[num] = ctr.get(num, 0) + 1
        nums = set(nums)
        paths = [([num], { **ctr, num: ctr[num] - 1 }, 1) for num in nums]
        while paths[0][2] < n:
            curr, currCtr, l = paths.pop(0)
            for num in nums:
                if currCtr[num] > 0:
                    paths.append((curr + [num], { **currCtr, num: currCtr[num] - 1 }, l + 1))
        return [perm[0] for perm in paths]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)