Permutations II — LeetCode 47 Python Solution

MediumArrayBacktrackingSorting
Problem
#47
Reading time
4 min

The problem

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Example

Input
nums = [1,1,2]
Output
[[1,1,2],

Python solution

Python
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def dfs(i: int):
            if i == n:
                ans.append(t[:])
                return
            for j in range(n):
                if vis[j] or (j and nums[j] == nums[j - 1] and not vis[j - 1]):
                    continue
                t[i] = nums[j]
                vis[j] = True
                dfs(i + 1)
                vis[j] = False

        n = len(nums)
        nums.sort()
        ans = []
        t = [0] * n
        vis = [False] * n
        dfs(0)
        return ans

Complexity

MeasureComplexity
TimeO(n \times n!)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 47. Permutations II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 47. Permutations II?
LeetCode 47. Permutations II is rated Medium on LeetCode.
What is the time complexity of LeetCode 47. Permutations II?
The Python solution on this page runs in O(n \times n!).
What is the space complexity of LeetCode 47. Permutations II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 47. Permutations II cover?
LeetCode 47. Permutations II is tagged Array, Backtracking and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview