Generate All Subsets Powerset in DSA C# - Time & Space Complexity
When we generate all subsets (powerset) of a set, we want to know how the work grows as the set gets bigger.
We ask: How many steps does it take to list every subset?
Analyze the time complexity of the following code snippet.
public IList<IList<int>> Subsets(int[] nums) {
var result = new List<IList<int>>();
Generate(0, new List<int>(), nums, result);
return result;
}
private void Generate(int index, List<int> current, int[] nums, IList<IList<int>> result) {
if (index == nums.Length) {
result.Add(new List<int>(current));
return;
}
Generate(index + 1, current, nums, result);
current.Add(nums[index]);
Generate(index + 1, current, nums, result);
current.RemoveAt(current.Count - 1);
}
This code generates all subsets of the input array by choosing to include or exclude each element recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls that branch twice at each element.
- How many times: For n elements, there are 2 choices (include/exclude) per element, leading to 2^n calls.
Each element doubles the number of subsets, so the work grows very fast.
| 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: Doubling the input size roughly squares the work, showing exponential growth.
Time Complexity: O(n * 2^n)
This means the time grows exponentially with the number of elements, multiplied by the size of each subset created.
[X] Wrong: "Generating all subsets is just O(n) because we visit each element once."
[OK] Correct: Each element creates two branches (include or exclude), so the total subsets grow exponentially, not linearly.
Understanding this exponential growth helps you explain why some problems need careful handling and why generating all subsets is costly but sometimes necessary.
"What if we only wanted subsets of a fixed size k? How would the time complexity change?"
Practice
powerset mean in the context of subsets?Solution
Step 1: Understand the definition of powerset
The powerset of a set is the collection of all subsets, including the empty set and the set itself.Step 2: Compare options with definition
All possible subsets of a given set including empty and full set correctly describes all subsets including empty and full set. Other options limit subsets incorrectly.Final Answer:
All possible subsets of a given set including empty and full set -> Option BQuick Check:
powerset = all subsets [OK]
- Thinking powerset excludes empty set
- Confusing powerset with subsets of fixed size
- Ignoring the full set as a subset
Solution
Step 1: Identify the correct data structure for subsets
Each subset is a list of integers, so the collection of subsets should be a list of lists of integers.Step 2: Check each option's type
var subsets = new List(); uses List, which is correct. var subsets = new List<int>(); is List<int> (single list), var subsets = new List(); is List (array instead of list), var subsets = new List<int>(); subsets.Add(new List<int>()); mixes types incorrectly.Final Answer:
var subsets = new List(); -> Option AQuick Check:
List of list<int> for subsets [OK]
- Using List<int> instead of List
- Confusing arrays with lists
- Adding elements before initializing list
var nums = new int[] {1, 2};
var subsets = new List { new List<int>() };
foreach (var num in nums) {
int count = subsets.Count;
for (int i = 0; i < count; i++) {
var newSubset = new List<int>(subsets[i]) { num };
subsets.Add(newSubset);
}
}
foreach (var subset in subsets) {
Console.Write(string.Join(",", subset) + "|");
}Solution
Step 1: Trace initial subsets list
Initially subsets contains one empty list: [[]].Step 2: Process first number 1
For num=1, we add subsets: [1] to subsets. Now subsets = [[], [1]].Step 3: Process second number 2
For num=2, we add subsets: [2] and [1,2]. Now subsets = [[], [1], [2], [1,2]].Step 4: Print all subsets
Empty subset prints as "|", so output is "| |1|2|1,2|".Final Answer:
| |1|2|1,2| -> Option CQuick Check:
All subsets printed with empty first [OK]
- Ignoring empty subset in output
- Not copying subsets before adding new element
- Miscounting subsets during iteration
var nums = new int[] {1, 2};
var subsets = new List();
foreach (var num in nums) {
int count = subsets.Count;
for (int i = 0; i < count; i++) {
var newSubset = new List<int>(subsets[i]) { num };
subsets.Add(newSubset);
}
}Solution
Step 1: Check initialization of subsets
subsets is empty initially, so count is 0 and inner loop never runs.Step 2: Understand consequence
Without starting with empty subset, no new subsets are generated.Final Answer:
subsets list is not initialized with empty subset -> Option AQuick Check:
Empty subset needed to start [OK]
- Not adding empty subset before loop
- Assuming subsets auto-initialize
- Modifying list while iterating without base case
nums = new List<int> {1, 2, 2}, which modification to the standard powerset generation code will correctly generate all unique subsets without duplicates?Solution
Step 1: Understand duplicate problem
Input has duplicates (2 appears twice), so normal powerset code generates duplicate subsets.Step 2: Identify correct approach
Sorting nums allows skipping duplicates during subset generation to avoid repeated subsets.Step 3: Evaluate options
Sort nums and skip adding duplicate elements in inner loop correctly describes sorting and skipping duplicates. Use a HashSet to store subsets as strings to avoid duplicates is workaround but less efficient. Add all subsets without any check; duplicates will be filtered later allows duplicates. Use a Dictionary to map counts and generate subsets is unrelated.Final Answer:
Sort nums and skip adding duplicate elements in inner loop -> Option DQuick Check:
Sort and skip duplicates to avoid repeats [OK]
- Not sorting input before generating subsets
- Trying to remove duplicates after generation
- Using complex data structures unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
