MediumNo. 0090

Subsets II — LeetCode 90 Python Solution

Topics
Bit Manipulation, Array, Backtracking
On a study list
NeetCode 150
Reading time
3 min

The problem

Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets.

Example

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

Python solution

PythonSolution
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        def dfs(i: int):
            if i == len(nums):
                ans.append(t[:])
                return
            t.append(nums[i])
            dfs(i + 1)
            x = t.pop()
            while i + 1 < len(nums) and nums[i + 1] == x:
                i += 1
            dfs(i + 1)

        nums.sort()
        ans = []
        t = []
        dfs(0)
        return ans

Complexity

Time
O(n × 2n)
Space · auxiliary
O(n)

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 90. Subsets 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 90. Subsets II?

LeetCode 90. Subsets II is rated Medium on LeetCode.

What is the time complexity of LeetCode 90. Subsets II?

The Python solution on this page runs in O(n × 2n).

What is the space complexity of LeetCode 90. Subsets II?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 90. Subsets II cover?

LeetCode 90. Subsets II is tagged Bit Manipulation, Array and Backtracking 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.

Free to download. Check it runs on your machine, then pick a plan.