Subsets — LeetCode 78 Python Solution

MediumBit ManipulationArrayBacktracking
Problem
#78
Reading time
3 min

The problem

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets.

Example

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

Python solution

Python
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def dfs(i: int):
            if i == len(nums):
                ans.append(t[:])
                return
            dfs(i + 1)
            t.append(nums[i])
            dfs(i + 1)
            t.pop()

        ans = []
        t = []
        dfs(0)
        return ans

Complexity

MeasureComplexity
TimeO(n \times 2^n)
SpaceO(n) auxiliary

Pattern: Backtracking

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

On study lists

This problem is on NeetCode 150 and Grind 75.

Frequently asked questions

How hard is LeetCode 78. Subsets?
LeetCode 78. Subsets is rated Medium on LeetCode.
What is the time complexity of LeetCode 78. Subsets?
The Python solution on this page runs in O(n \times 2^n).
What is the space complexity of LeetCode 78. Subsets?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 78. Subsets cover?
LeetCode 78. Subsets 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.

Get Stealth Interview