Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding all possible subsets of an array in JavaScript
Finding all possible subsets of an array is a common algorithmic problem. A subset is any combination of elements from the original array, including the empty set and the full array itself.
For an array of n elements, there are 2^n possible subsets. This is because each element can either be included or excluded from a subset.
For example, if the input array is:
const arr = [1, 2, 3];
The output should contain all possible subsets:
[ [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]
Using Iterative Approach
This method builds subsets incrementally by adding each new element to all existing subsets:
const findAllSubsets = (arr = []) => {
const result = [[]]; // Start with empty subset
for (let i = 0; i < arr.length; i++) {
const currentLength = result.length;
// Add current element to all existing subsets
for (let j = 0; j < currentLength; j++) {
const newSubset = [...result[j], arr[i]];
result.push(newSubset);
}
}
return result;
};
const arr = [1, 2, 3];
console.log(findAllSubsets(arr));
[ [], [ 1 ], [ 2 ], [ 1, 2 ], [ 3 ], [ 1, 3 ], [ 2, 3 ], [ 1, 2, 3 ] ]
Using Bit Manipulation
This approach uses binary representation where each bit indicates whether to include an element:
const findAllSubsetsBinary = (arr = []) => {
const result = [];
const totalSubsets = Math.pow(2, arr.length);
for (let i = 0; i < totalSubsets; i++) {
const subset = [];
for (let j = 0; j < arr.length; j++) {
// Check if jth bit is set in i
if (i & (1 << j)) {
subset.push(arr[j]);
}
}
result.push(subset);
}
return result;
};
const arr2 = [1, 2, 3];
console.log(findAllSubsetsBinary(arr2));
[ [], [ 1 ], [ 2 ], [ 1, 2 ], [ 3 ], [ 1, 3 ], [ 2, 3 ], [ 1, 2, 3 ] ]
How It Works
The iterative approach starts with an empty subset and progressively adds each element to all existing subsets. For each new element, it doubles the number of subsets.
The binary approach treats each subset as a binary number where bit position represents whether to include that element. For array [1,2,3], binary 101 means include elements at positions 0 and 2, giving subset [1,3].
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Iterative | O(2^n) | O(2^n) | High |
| Bit Manipulation | O(2^n) | O(2^n) | Medium |
Conclusion
Both approaches generate all possible subsets with the same complexity. The iterative method is more intuitive, while bit manipulation is more compact and demonstrates clever use of binary operations.
