DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay