← Back to Algorithms, page 3

algorithms-0048 · Medium fresher

Generate all subsets of a list using backtracking, and then handle a list that contains duplicate values.

Each element is either in or out, so there are 2^n subsets. Backtracking builds a current subset: record it, then for each later index choose that element, recurse, and undo the choice. For duplicates, sort first and skip a value equal to the previous one at the same depth, which removes repeated subsets without a set of results.

Full answer

Problem

Given a list nums, return every subset (the power set) in any order.

Example: [1, 2, 3] gives [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3].

Follow-up: with duplicates, [1, 2, 2] should give 6 distinct subsets, not 8: [], [1], [1, 2], [1, 2, 2], [2], [2, 2].

Constraints: 0 <= len(nums) <= 10.

Brute force

Bitmasks: for each mask from 0 to 2^n - 1, include nums[i] when bit i is set. Also O(n x 2^n). For duplicates, generating everything and deduplicating with a set of sorted tuples works but wastes effort.

Optimal approach

backtrack(start):

  1. Append a copy of current to the result (every partial choice is a subset).
  2. For i from start to the end: append nums[i], call backtrack(i + 1), pop it.

Duplicates: sort nums, and inside the loop skip i when i > start and nums[i] == nums[i - 1].

Why it works

Starting each loop at start means elements are always chosen in index order, so each subset is produced exactly once, as the path to one node of the recursion tree. Undoing the choice (pop) restores current for the next sibling.

Duplicate skipping: at a given depth, choosing the first or the second of two equal values leads to identical subsets. Sorting puts equal values together, and skipping later equal siblings keeps only the first branch. The condition i > start still allows taking both copies along one path ([2, 2]).

Complexity

O(n x 2^n) time: 2^n subsets, each copied in up to O(n). O(n) recursion depth, plus the output itself.

Code

python
def subsets(nums):
    """All subsets of distinct values via backtracking: include or skip each item."""
    result, current = [], []

    def backtrack(start):
        result.append(list(current))          # every partial choice is a subset
        for i in range(start, len(nums)):
            current.append(nums[i])           # choose
            backtrack(i + 1)                  # explore
            current.pop()                     # un-choose

    backtrack(0)
    return result


def subsets_with_dup(nums):
    """Subsets when nums may contain duplicates: sort, then skip equal siblings."""
    nums = sorted(nums)
    result, current = [], []

    def backtrack(start):
        result.append(list(current))
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            current.append(nums[i])
            backtrack(i + 1)
            current.pop()

    backtrack(0)
    return result


if __name__ == "__main__":
    assert sorted(subsets([1, 2, 3])) == sorted(
        [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]])
    assert subsets([]) == [[]]
    assert len(subsets(list(range(10)))) == 2 ** 10
    assert sorted(subsets_with_dup([1, 2, 2])) == sorted(
        [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]])
    assert subsets_with_dup([0]) == [[], [0]]
    print("all tests passed")

Save as a48_subsets.py and run python3 a48_subsets.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input returns [[]]. Appending current without copying stores the same list object many times, which ends up empty. With duplicates, skipping with i > 0 instead of i > start wrongly removes [2, 2].

Pattern

Backtracking template: choose, explore, un-choose. The same template generates combinations of size k, permutations, combination sum and palindrome partitions.

python
def subsets(nums):
    """All subsets of distinct values via backtracking: include or skip each item."""
    result, current = [], []

    def backtrack(start):
        result.append(list(current))          # every partial choice is a subset
        for i in range(start, len(nums)):
            current.append(nums[i])           # choose
            backtrack(i + 1)                  # explore
            current.pop()                     # un-choose

    backtrack(0)
    return result


def subsets_with_dup(nums):
    """Subsets when nums may contain duplicates: sort, then skip equal siblings."""
    nums = sorted(nums)
    result, current = [], []

    def backtrack(start):
        result.append(list(current))
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            current.append(nums[i])
            backtrack(i + 1)
            current.pop()

    backtrack(0)
    return result


if __name__ == "__main__":
    assert sorted(subsets([1, 2, 3])) == sorted(
        [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]])
    assert subsets([]) == [[]]
    assert len(subsets(list(range(10)))) == 2 ** 10
    assert sorted(subsets_with_dup([1, 2, 2])) == sorted(
        [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]])
    assert subsets_with_dup([0]) == [[], [0]]
    print("all tests passed")

Backtracking with choose, explore and un-choose; the duplicate version sorts and skips equal siblings.

Complexity

Time: O(n * 2^n). Space: O(n) recursion depth, plus O(n * 2^n) output. Bitmask enumeration has the same bound.

By level

Fresher: Writes the include-or-skip recursion and lists the subsets for a short example. Should state that there are 2^n subsets.

Mid: Uses the loop-from-start template, handles duplicates with sorting and skipping, and explains the recursion tree. Tests a list with three equal values.

Senior: Compares backtracking with bitmasks and iterative generation, discusses output-sensitive complexity and pruning strategies. Can explain why the output size dominates the running time.

Key points

  • 2^n subsets
  • Record current at every node of the recursion tree
  • Choose, explore, un-choose
  • Loop from start so each subset appears once
  • Sort and skip equal siblings for duplicates

Common mistakes

  • Appending current without copying
  • Skipping duplicates with i > 0 instead of i > start
  • Deduplicating with a set instead of pruning
  • Forgetting to pop after the recursive call

Follow-ups

  • How would you generate only subsets of size k?
  • How do you generate all permutations?
  • How would you solve combination sum?

Tips

  • State 2^n before coding
  • Draw the recursion tree for three elements
  • Test [1, 2, 2]

Evaluation rubric

  • Correct backtracking
  • Correct duplicate handling
  • Correct complexity
  • Copies the current subset