Generate All Subsets Powerset in DSA Javascript - 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.
function generateSubsets(nums) {
const result = [];
function backtrack(start, subset) {
result.push([...subset]);
for (let i = start; i < nums.length; i++) {
subset.push(nums[i]);
backtrack(i + 1, subset);
subset.pop();
}
}
backtrack(0, []);
return result;
}
This code finds all possible subsets (the powerset) of the input array by exploring each choice recursively.
- Primary operation: Recursive calls that explore each subset possibility.
- How many times: Each element can be either included or excluded, so the recursion explores 2^n subsets.
As the input size grows, the number of subsets doubles for each new element added.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,024 subsets explored |
| 20 | About 1,048,576 subsets explored |
| 30 | About 1,073,741,824 subsets explored |
Pattern observation: The work doubles with each additional element, growing very fast.
Time Complexity: O(n * 2^n)
This means the time grows very fast because we explore all subsets, and each subset can take up to n steps to build.
[X] Wrong: "Generating subsets is just a simple loop over the array, so it's O(n)."
[OK] Correct: Each element doubles the number of subsets, so the total work grows exponentially, not linearly.
Understanding this complexity helps you explain why some problems need exponential time and shows your grasp of recursion and combinatorics.
"What if we only wanted subsets of a fixed size k? How would the time complexity change?"
Practice
powerset mean in the context of sets?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 the definition
All possible subsets of a set including the empty set correctly describes the powerset as all possible subsets including the empty set. Other options describe only parts or incorrect subsets.Final Answer:
All possible subsets of a set including the empty set -> Option BQuick Check:
powerset = all subsets [OK]
- Thinking powerset excludes empty set
- Confusing powerset with subsets of fixed size
- Assuming powerset is just the original set
arr?Solution
Step 1: Check valid JavaScript function syntax
function generateSubsets(arr) { ... } uses correct syntax with one parameter named arr. function generateSubsets(arr[]) { ... } uses invalid syntax with arr[]. function generateSubsets() { ... } has no parameters, which is incomplete for this task. function generateSubsets(arr, subsets) { ... } has two parameters which might be valid but is not the standard signature for generating subsets.Step 2: Choose the most appropriate signature
function generateSubsets(arr) { ... } is the standard and correct way to define a function that takes an array to generate subsets.Final Answer:
function generateSubsets(arr) { ... } -> Option DQuick Check:
Correct function syntax = function generateSubsets(arr) { ... } [OK]
- Using array syntax in parameter list (arr[])
- Omitting required parameters
- Adding unnecessary parameters without explanation
function subsets(nums) {
let result = [[]];
for (const num of nums) {
const newSubsets = [];
for (const subset of result) {
newSubsets.push([...subset, num]);
}
result.push(...newSubsets);
}
return result;
}
console.log(subsets([1, 2]));Solution
Step 1: Trace the initial result and loop
Initially, result = [[]]. For num=1, newSubsets = [[1]], result becomes [[], [1]]. For num=2, newSubsets = [[2], [1, 2]], result becomes [[], [1], [2], [1, 2]].Step 2: Confirm final output
The function returns [[], [1], [2], [1, 2]] which matches [[], [1], [2], [1, 2]] exactly.Final Answer:
[[], [1], [2], [1, 2]] -> Option AQuick Check:
All subsets of [1,2] = [[], [1], [2], [1, 2]] [OK]
- Missing empty subset in output
- Not adding new subsets correctly
- Confusing order of subsets
nums:function getSubsets(nums) {
let result = [];
for (let num of nums) {
let newSubsets = [];
for (let subset of result) {
newSubsets.push(subset.concat(num));
}
result = result.concat(newSubsets);
}
return result;
}
console.log(getSubsets([1, 2]));Solution
Step 1: Check initial value of result
The code initializes result as an empty array []. It should start with [[]] to include the empty subset, otherwise no subsets are generated.Step 2: Understand impact of initial value
Without the empty subset, the inner loop never runs on first iteration, so no subsets are created. Adding [[]] fixes this.Final Answer:
The initial result should contain the empty subset [[]] -> Option AQuick Check:
Start with [[]] to generate subsets [OK]
- Starting with empty array instead of [[]]
- Confusing concat and push usage
- Looping over wrong array
nums = [1, 2, 2], which code modification correctly generates all unique subsets (no duplicates) using the powerset approach?Solution
Step 1: Understand the problem with duplicates
Array [1, 2, 2] has duplicates. Generating subsets normally will create duplicate subsets like [2] twice.Step 2: Apply sorting and skipping duplicates
Sorting nums makes duplicates adjacent. During subset generation, skip adding subsets that duplicate previous ones to avoid duplicates in result.Final Answer:
Sort nums first, then skip adding duplicate subsets during generation -> Option CQuick Check:
Sort and skip duplicates to get unique subsets [OK]
- Ignoring duplicates causing repeated subsets
- Removing duplicates from input changes problem
- Using Set of strings can be inefficient or incorrect
Ready to prove it?
Pass the test and this pattern moves unknown
