Taro Logo

Subsets

#2 Most AskedMedium
212 views
Topics:
ArraysRecursionBit Manipulation

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input array `nums`, and should I expect any memory limits for the output since the number of subsets grows exponentially?
  2. Can the input array contain negative numbers and zeros, or are we strictly dealing with positive integers?
  3. Are the elements in the input array guaranteed to be unique, or could there be duplicate values in `nums`?
  4. Does the order of subsets in the final result matter, or can they be returned in any order?
  5. How should an empty input array be handled—should it return a list containing just the empty subset `[[]]`?

Brute Force Solution

Approach

Imagine you have a collection of distinct items and you want to discover every possible combination of them, from empty collections to the full set. The brute force strategy involves examining every single item and deciding for each one whether to include it or leave it out, ensuring you map out every conceivable grouping.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in your collection.
  2. For this first item, write down two paths: one where you include it in a new group, and one where you leave it out.
  3. Move on to the next item in the collection and apply the exact same two choices to every group you have created so far.
  4. Continue this process item by item, branching out your choices every time you encounter a new element.
  5. As you make these decisions, your collection of groups will grow to cover every possible combination of items.
  6. Once you have gone through every single item, collect all the groups you have formed.
  7. Review your final list to ensure you have captured every unique combination, from the group with nothing in it all the way up to the group containing everything.

Code Implementation

def subsets(input_numbers):
    # Initialize with an empty group to start building combinations from the ground up
    all_subsets = [[]]

    for current_number in input_numbers:
        # Expand existing groups by adding the current number to each to form new combinations
        additional_subsets = []

        for existing_subset in all_subsets:
            new_subset = existing_subset + [current_number]
            additional_subsets.append(new_subset)

        # Combine newly formed groups with previous ones to maintain all discovered combinations
        all_subsets.extend(additional_subsets)

    return all_subsets

Big(O) Analysis

Time Complexity
O(2^n) – For each of the n elements in the input collection, we branch into two choices: either including the element or leaving it out, which doubles the number of subsets at each step. Starting with 1 empty set, processing the first element creates 2 sets, the second element creates 4 sets, and continuing this process results in 2 to the power of n total subsets. Since we must generate and store every single one of these combinations, the total operations and memory scale proportionally to 2 to the power of n, simplifying to O(2^n).
Space Complexity
O(2^N * N) – To determine the auxiliary space complexity, we must examine the recursion stack and the memory required to store the intermediate paths and final output groups. The recursion stack grows to a maximum depth of N, corresponding to the total number of items in the input collection. Additionally, the algorithm generates 2^N unique subsets, each containing up to N elements as it branches out to include or leave out every item. Combining the storage for these subsets with the maximum recursion depth yields a total auxiliary space complexity that scales exponentially with the input size N.

Optimal Solution

Approach

To find every possible group you can make from a collection of items, you can build them step-by-step by deciding whether to include each item or leave it out. The strategy involves exploring all combinations methodically by branching out at each choice point, making sure you capture every unique gathering from the largest group down to nothing at all.

Here's how the algorithm would work step-by-step:

  1. Imagine standing in front of a table of unique items and a blank sheet of paper representing your current collection.
  2. Look at the first item on the table and make your first major choice: either you keep this item or you pass on it.
  3. If you decide to keep it, add it to your paper and explore all the further combinations you can make with the remaining items.
  4. Once you have explored all possibilities with that item included, undo your choice by removing it from your paper.
  5. Now, move on to explore all the possibilities where that item was never included in the first place.
  6. Repeat this branching decision process for every single item until you have evaluated every possible combination of keeps and passes.
  7. Collect every unique group of items you formed along the way as a valid result to complete your task.

Code Implementation

class Solution:
    def subsets(self, input_numbers: list[int]) -> list[list[int]]:
        all_subsets = []
        
        # We build subsets incrementally by deciding whether to include each element.
        def backtrack(start_index: int, current_subset: list[int]):
            all_subsets.append(list(current_subset))
            
            for current_index in range(start_index, len(input_numbers)):
                current_subset.append(input_numbers[current_index])
                
                # Recursively explore all further combinations with the current item included.
                backtrack(current_index + 1, current_subset)
                
                # Backtrack by removing the item to explore paths without it.
                current_subset.pop()
                
        backtrack(0, [])
        
        return all_subsets

Big(O) Analysis

Time Complexity
O(2^n) – For each of the n elements in the input array, the algorithm makes a binary choice to either include or exclude it in the subset. This branching decision process creates a recursion tree that doubles in size with each new element, resulting in 2^n total possible subsets. Since we must visit and construct every single subset of which there are 2^n, the total operations approximate n times 2^n if copying takes linear time, or simply O(2^n) to generate all states.
Space Complexity
O(N * 2^N) – The auxiliary space is dominated by the recursion stack frames which reach a maximum depth of N, and the temporary path list that grows up to size N during each branch exploration. Furthermore, storing the 2^N total subsets in the final output list significantly drives up the memory consumption. As the input size N increases, these combined data structures require exponential extra space relative to N.

Edge Cases

Empty input array nums where length is zero
How to Handle:
The backtracking or iterative algorithm should correctly output a list containing only the empty subset.
Single element array containing one number
How to Handle:
The algorithm should produce exactly two subsets consisting of the empty set and the single element set.
Maximum size input array up to the upper constraint limit
How to Handle:
Since the output size grows exponentially with two to the power of n, execution will hit time and memory limits for large n.
Input array containing negative integers and zero
How to Handle:
Standard backtracking treats negative numbers and zeros just like positive numbers without affecting subset generation logic.
Recursion depth limits for deeply nested recursive calls
How to Handle:
The maximum recursion depth is bounded by the length of the array preventing stack overflow under normal constraints.
Order independence in the returned subsets
How to Handle:
The problem accepts subsets in any order so standard lexicographical generation satisfies the requirement without extra sorting.
0/1037 completed