Problem Definition

Given an array of integers which may contain duplicates, return all possible subsets of the array.

This problem is a variation of Subsets, except the list may contain duplicates.


Examples

Some test cases to verify our solution.

exp = [[],[1],[1,2],[1,2,2],[2],[2,2]]
act = subsets([1, 2, 2])
for l in exp:
    assert l in act
assert len(exp) == len(act)

exp = [[], [0]]
act = subsets([0])
for l in exp:
    assert l in act
assert len(exp) == len(act)

Backtracking Solution

We implement a DFS with backtracking to avoid duplicates. First we'll sort our input list to group numbers together. We will use a start variable to track where the previous path layer ends. Then if the current index is greater than start and the current item is equal to the previous in the list, this indicates we are about to create a duplicate entry. For example, if we are given [1, 2, 2] as the input, then on the internal dfs call below, we will have start == 1 and the internal for loop will look at [2, 2]. We will create a new stack frame for the first two because i = 1 is not greater than start == 1. This stack frame will continue creating sets with the base path [1, 2]. For the second 2, the index will be 2, which is greater than 1 and nums[2] == nums[1]; so we will skip creating a new stack frame with a duplicate path [1, 2].

def subsets(nums: list[int]) -> list[list[int]]:
    n = len(nums)
    nums.sort()
    ans = []
    def dfs(start, path):
        ans.append(path.copy())
        for i in range(start, n):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            dfs(i + 1, path)
            path.pop()
    dfs(0, [])
    return ans

Backtracking Solution Complexity

Let $n =$ len(nums).

Sorting nums initially takes $O(n \log n)$ time. In the worst case (where all elements are unique), there are $2^n$ subsets. For each subset, copying the current path into ans takes $O(n)$ time. The number of recursive calls is bounded by the number of subsets generated, leading to an overall runtime complexity of $O(n \cdot 2^n)$.

Auxiliary space complexity is $O(n)$ due to the recursive call stack depth and the temporary path list (excluding the memory required to store the $O(n \cdot 2^n)$ output).


Improved Iterative (Cascading) Solution

We can improve upon the recursive solution by generating subsets iteratively (also known as cascading), eliminating recursion overhead and reducing auxiliary space complexity to $O(1)$.

We begin by sorting nums so duplicate numbers are adjacent, and initialize our result with the empty subset: ans = [[]]. When considering the element at index i:

  • If nums[i] is unique (different from nums[i - 1]), we can safely duplicate and append nums[i] to all existing subsets in ans.
  • If nums[i] is a duplicate (nums[i] == nums[i - 1]), appending it to all existing subsets would re-create subsets already created in earlier steps. Therefore, we only append nums[i] to the subsets that were added during the immediately preceding step.

By maintaining start_idx and prev_size, we selectively extend only the newly generated subsets whenever a duplicate is encountered.

def subsets(nums: list[int]) -> list[list[int]]:
    nums.sort()
    ans = [[]]
    prev_size = 0
    for i in range(len(nums)):
        # If current element is duplicate of previous, only append to subsets added in previous step
        start_idx = prev_size if i > 0 and nums[i] == nums[i - 1] else 0
        prev_size = len(ans)
        for j in range(start_idx, prev_size):
            ans.append(ans[j] + [nums[i]])
    return ans

Improved Solution Complexity

Let $n =$ len(nums).

Runtime complexity is $O(n \cdot 2^n)$ in the worst case (when all elements are distinct). When duplicate elements exist, fewer than $2^n$ subsets are generated, reducing both iteration counts and copy operations proportionally.

Auxiliary space complexity is $O(1)$ (beyond the output list itself), as no recursion stack frames or additional buffer structures are required.