Generate All Subsets Powerset in DSA Python - Time & Space Complexity
When we generate all subsets of a set, we want to know how the time needed grows as the set gets bigger.
We ask: How does the work increase when the input size increases?
Analyze the time complexity of the following code snippet.
def generate_subsets(nums):
result = []
def backtrack(start, path):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
backtrack(0, [])
return result
This code finds all possible subsets of the input list by exploring each choice step-by-step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls that explore subsets by adding or skipping elements.
- How many times: Each element can be either included or excluded, so the recursion explores 2n paths.
Each new element doubles the number of subsets to explore.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,024 subsets |
| 20 | About 1,048,576 subsets |
| 30 | About 1,073,741,824 subsets |
Pattern observation: The work doubles with each added element, growing very fast.
Time Complexity: O(n * 2n)
This means the time grows very fast because we explore every subset, and each subset can take up to n steps to build.
[X] Wrong: "Generating subsets is just O(n) because we loop through the list once."
[OK] Correct: We do more than one loop; we explore all combinations, which grow exponentially, not linearly.
Understanding this complexity helps you explain why some problems take longer and shows you can reason about exponential growth clearly.
"What if we only wanted subsets of a fixed size k? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of powerset
The powerset of a set is the collection of all subsets of that set, including the empty set and the set itself.Step 2: Compare options with definition
All possible subsets including empty and full set correctly states all possible subsets are included. Other options limit subsets incorrectly.Final Answer:
All possible subsets including empty and full set -> Option DQuick Check:
Powerset = All subsets [OK]
- Thinking powerset excludes empty set
- Confusing powerset with subsets of certain size
- Assuming powerset only includes full set
Solution
Step 1: Identify the correct data structure for storing subsets
Subsets are typically stored in a list because order and duplicates matter for powerset generation.Step 2: Analyze each option
subsets = [] uses an empty list []. subsets = {} uses a dictionary {}, which is incorrect. subsets = () uses a tuple (), which is immutable. subsets = set() uses a set(), which cannot store duplicates or ordered subsets.Final Answer:
subsets = [] -> Option CQuick Check:
Use list [] for subsets storage [OK]
- Using {} which creates a dictionary, not a list
- Using () which is immutable tuple
- Using set() which loses order and duplicates
def powerset(nums):
result = [[]]
for num in nums:
result += [curr + [num] for curr in result]
return result
print(powerset([1, 2]))Solution
Step 1: Trace initial result and loop iterations
Start with result = [[]]. For num=1, add subsets: [] + [1] = [1], so result = [[], [1]]. For num=2, add subsets: [] + [2] = [2], [1] + [2] = [1, 2], so result = [[], [1], [2], [1, 2]].Step 2: Confirm final output list
The final list contains all subsets: empty, single elements, and full set.Final Answer:
[[], [1], [2], [1, 2]] -> Option BQuick Check:
All subsets of [1,2] = [[], [1], [2], [1, 2]] [OK]
- Missing empty subset [] in output
- Not combining previous subsets with new element
- Confusing order of subsets
def powerset(nums):
result = []
for num in nums:
for curr in result:
result.append(curr + [num])
return result
print(powerset([1, 2]))Solution
Step 1: Check initial value of result
result is initialized as empty list []. The inner loop for curr in result will not run because result is empty.Step 2: Understand consequence on output
Since inner loop never runs, no subsets are added. The function returns empty list [].Final Answer:
result list is empty initially, so loop never runs -> Option AQuick Check:
Empty result means no subsets generated [OK]
- Not initializing result with [[]]
- Modifying list while iterating (can cause bugs)
- Forgetting to add empty subset initially
nums = [1, 2, 2], which code modification correctly generates the powerset without duplicate subsets?Solution
Step 1: Understand the problem with duplicates
Input has duplicates (2 appears twice). Powerset generation can create duplicate subsets if duplicates are not handled.Step 2: Analyze options for handling duplicates
Use a set to store tuples of subsets to avoid duplicates uses a set of tuples which works but changes data type and order. Sort nums and skip duplicates during subset generation sorts nums and skips duplicates during recursion, which is standard and efficient. Use list comprehension without any checks ignores duplicates. Remove duplicates from nums before generating subsets removes duplicates, which changes the original set.Final Answer:
Sort nums and skip duplicates during subset generation -> Option AQuick Check:
Sort and skip duplicates to avoid repeated subsets [OK]
- Removing duplicates changes original data meaning
- Using sets loses subset order
- Ignoring duplicates causes repeated subsets
Ready to prove it?
Pass the test and this pattern moves unknown
