Subsets (LeetCode 78): Solution and Explanation

Medium
Array
Backtracking
Bit Manipulation

Given an array of distinct integers, return every possible subset, including the empty set and the full array. No subset may appear twice, and the order of the output does not matter.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Every subset can be described by a yes or no decision for each element: is nums[0] in it, is nums[1] in it, and so on. With n elements that is n independent binary choices, so there are exactly 2^n subsets. Any correct solution has to produce all of them, and each can be up to n elements long, so O(n × 2^n) is the best possible.

Those binary decisions form a decision tree. At depth i you decide about nums[i], branching once to include it and once to exclude it. After n decisions you reach a leaf, and the elements you said yes to form one subset. A depth-first walk of this tree visits every leaf exactly once, so it generates every subset with no duplicates and no need for a seen set.

Backtracking lets you walk the tree with a single shared list. Append nums[i] and recurse to explore the include branch, then pop it and recurse again to explore the exclude branch. The pop restores the list to exactly what it was before the decision, so the two branches do not interfere with each other. At each leaf you save a copy, since the shared list will keep changing.

Approach: Include or exclude backtracking

  1. Create res for the results and a shared list subset for the current choices.
  2. Define dfs(i). If i >= len(nums), every element has been decided, so append a copy of subset to res and return.
  3. Include branch: append nums[i] to subset and call dfs(i + 1).
  4. Exclude branch: pop nums[i] from subset and call dfs(i + 1) again.
  5. Call dfs(0) and return res.

Step-by-step example

nums = [1,2,3]
  1. Include 1, include 2, include 3, then reach the end: record [1,2,3].
  2. Back at index 2, pop 3 and take the exclude branch: record [1,2].
  3. Back at index 1, pop 2. Now subset = [1]; include 3 to record [1,3], then exclude it to record [1].
  4. Back at index 0, pop 1. With subset = [], the same pattern records [2,3], [2], [3] and finally [].
  5. The result holds 8 = 2^3 subsets: [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3], [].

Code: Python, Java, C++

1class Solution:
2    def subsets(self, nums: List[int]) -> List[List[int]]:
3        res = []
4        subset = []
5        
6        def dfs(i):
7            if i >= len(nums):
8                res.append(subset.copy())
9                return
10            
11            # include nums[i]
12            subset.append(nums[i])
13            dfs(i + 1)
14            
15            # exclude nums[i]
16            subset.pop()
17            dfs(i + 1)
18            
19        dfs(0)
20        return res

Time and space complexity

Time

O(n × 2^n)

The decision tree has 2^n leaves, and at each leaf the code copies a list of up to n elements. Internal nodes do constant work, so copying dominates.

Space

O(n)

Excluding the output, the recursion is n levels deep and subset holds at most n values. The output itself takes O(n × 2^n). For the largest input of 10 elements that is 1,024 lists.

Other approaches

Iterative cascading (time O(n × 2^n), space O(n × 2^n))

Start with [[]]. For each number, take every subset already in the result, copy it with the number appended, and add the copies. After all numbers the list holds every subset. It is short and avoids recursion.

Bitmask enumeration (time O(n × 2^n), space O(n))

Loop a mask from 0 to 2^n - 1 and include nums[j] whenever bit j of the mask is set. Each mask maps to one subset. It is very direct and works well when n is small, as it is here.

Common mistakes

  • Appending subset instead of subset.copy(), so every result is the same list that ends up empty.
  • Forgetting the pop before the exclude branch, which carries nums[i] into subsets that were supposed to skip it.
  • Recording subsets only when they are non-empty, which drops the empty set that the problem requires.
  • Applying this code to input with duplicates, which produces repeated subsets. That variant needs sorting and skipping equal neighbors.

Frequently asked questions

How many subsets does an array of n elements have?

Exactly 2^n, because each element is independently either in or out of a subset. For n = 10, the largest input here, that is 1,024 subsets.

What is the time complexity of generating subsets?

It is O(n × 2^n). There are 2^n subsets and building or copying each one can take up to n steps, which is also the size of the output.

Backtracking or bitmask for subsets?

Both have the same complexity. Bitmasks are compact for small n, while backtracking generalizes better to variants with duplicates or constraints, such as combination sums, where you want to prune branches early.

How do you handle duplicate elements?

Sort the array first. When you decide to exclude a value, skip past all copies of it before recursing, so the same subset is never generated through two different branches.