← Whiteboard questions

Subsets

List every possible selection from a set of numbers

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A list nums holds distinct whole numbers. Return every subset of nums, including the empty subset and nums itself. Inside each subset, keep the numbers in the order they have in nums. List the subsets in any order. No subset may appear twice.

Examples

Input nums = [4, 1, 7]
Output [[], [4], [4, 1], [4, 1, 7], [4, 7], [1], [1, 7], [7]]
Why the empty subset, three single numbers, three pairs and the whole list make 8 subsets.
Input nums = [5]
Output [[], [5]]
Why one number gives the empty subset and the subset with that number.
Input nums = [-2, 0]
Output [[], [-2], [-2, 0], [0]]
Why negative numbers and zero change nothing: 2 numbers give 4 subsets.

Constraints

Your answer must contain

Target Aim for O(n * 2^n) time, because the answer itself has that size.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Take one number from the list. What choices does it have when you build a subset?

Hint 2 the approach

Each choice leaves a smaller copy of the same question. Build one subset step by step, and record it after every step.

Hint 3 the key step

Keep one list for the current subset and a start position. Record a copy, then for each later position add it, recurse past it and remove it.

Walkthrough

Full walkthrough brute force to best

Brute force

Count from 0 to 2^n - 1. Each count is a mask: bit i says whether the number at position i is in the subset. Build every subset from its bits. This is correct and costs O(n * 2^n), the same order as the best method, because the answer holds n * 2^(n-1) numbers. It does not carry over to the next problems, where a branch must be cut early.

Best method

Treat each number as a choice: in or out. Keep the subset built so far in one list, and a start position that says which numbers may still be added. On every call, record a copy of the list. Then, for each position from start on, add that number, call again from the next position, and remove the number. A subset is only reached by adding its numbers in the order they have in the list, so each subset is recorded exactly once. This add, recurse, remove shape is called backtracking. The next problems use it with a test that cuts a branch early.

Hand trace

Run on [4, 1, 7]. Record []. Add 4 and record [4]. Add 1 and record [4, 1]. Add 7 and record [4, 1, 7]. Remove 7, then remove 1. Add 7 after the 4 and record [4, 7]. Remove 7, then remove 4. Add 1 and record [1]. Add 7 and record [1, 7]. Remove both. Add 7 and record [7]. The result is [], [4], [4, 1], [4, 1, 7], [4, 7], [1], [1, 7], [7].

Code

def subsets(nums):
    out = []
    path = []
    def go(start):
        out.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            go(i + 1)
            path.pop()
    go(0)
    return out

Time and memory

O(n * 2^n) time: there are 2^n subsets, and copying one takes up to n steps. Extra memory is O(n) for the list and the recursion, not counting the answer, which holds n * 2^(n-1) numbers.

Common mistakes

  • Recording the list itself, not a copy. Later removals change it, so every record ends up as the same empty list.
  • Forgetting to remove the number after the call. Later subsets then keep numbers from earlier ones.
  • Looping from position 0 instead of from start. The same subset then appears in several orders.

Related problems

More Backtracking problems
Subsets: hints, walkthrough and Python solution