Subsets

Pattern: Subsets

medium

Each element is either taken or skipped. Recurse over the elements with those two branches, and record the current bag at the end of every path. n elements give 2ⁿ subsets.

The problem

Given an array of different whole numbers, return all its subsets (the power set), including the empty one, with no subset listed twice. For example, [1, 2, 3] gives [], [1], [2], [3], [1, 2], [1, 3], [2, 3] and [1, 2, 3].

The function name subsets matches LeetCode. Use the link above for the exact statement and limits. Any order is accepted, so this guide's tests sort each subset and the list of subsets before comparing.

Think first

  • For one element, how many choices are there?
  • How many subsets do n elements have?
  • When is a subset complete?

Hints

    Brute force, and why it fails

    Count from 0 to 2ⁿ - 1 and use the bits of each number to pick elements: also O(2ⁿ × n), and a good alternative. Both must produce all 2ⁿ subsets, so neither can be faster.

    The key insight

    The take-or-skip tree has exactly one leaf per subset, so walking it lists each subset once.

    Dry run

    bag[]
    i0

    nums = [1, 2, 3]. Start with an empty bag at element 0.

    Step 1 of 4

    The plan

    function build(i, bag):
        if i == n: record a copy of bag; return
        add nums[i]; build(i + 1, bag); remove it
        build(i + 1, bag)
    build(0, [])
    

    Complexity

    Time
    O(2ⁿ × n)
    Space
    O(n)

    2ⁿ subsets, each copied in O(n). The recursion is n deep (not counting the output).

    Edge cases

    • One element: [] and itself.
    • Negative values: nothing changes.
    • The empty subset is always included.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> out = new ArrayList<>();
            build(nums, 0, new ArrayList<>(), out);
            return out;
        }
    
        private void build(int[] nums, int i, List<Integer> cur, List<List<Integer>> out) {
            if (i == nums.length) { out.add(new ArrayList<>(cur)); return; }   // every element decided: one subset
            cur.add(nums[i]);                               // branch 1: take nums[i]
            build(nums, i + 1, cur, out);
            cur.remove(cur.size() - 1);                     // branch 2: leave it out
            build(nums, i + 1, cur, out);
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> subsets(vector<int>& nums) {
            vector<vector<int>> out;
            vector<int> cur;
            build(nums, 0, cur, out);
            return out;
        }
    
        void build(vector<int>& nums, size_t i, vector<int>& cur, vector<vector<int>>& out) {
            if (i == nums.size()) { out.push_back(cur); return; }   // every element decided: one subset
            cur.push_back(nums[i]);                         // branch 1: take nums[i]
            build(nums, i + 1, cur, out);
            cur.pop_back();                                 // branch 2: leave it out
            build(nums, i + 1, cur, out);
        }
    };

    Python

    class Solution:
        def subsets(self, nums: list[int]) -> list[list[int]]:
            out = []
    
            def build(i: int, cur: list) -> None:
                if i == len(nums):
                    out.append(cur[:])              # every element decided: one subset
                    return
                cur.append(nums[i])                 # branch 1: take nums[i]
                build(i + 1, cur)
                cur.pop()                           # branch 2: leave it out
                build(i + 1, cur)
    
            build(0, [])
            return out

    Common mistakes

    • Recording the bag itself instead of a copy.
    • Forgetting the empty subset.
    • Using this on inputs with repeats, which lists equal subsets twice (see Subsets II).

    Similar problems