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 power set for a set in JavaScript Power Set
The power set of a set S is the set of all of the subsets of S, including the empty set and S itself. The power set of set S is denoted as P(S).
For example
If S = {x, y, z}, the subsets are:
{
{},
{x},
{y},
{z},
{x, y},
{x, z},
{y, z},
{x, y, z}
}
We need to write a JavaScript function that takes in an array as the only argument. The function should find and return the power set for the input array.
How It Works
The algorithm uses bit manipulation to generate all possible subsets. For a set of n elements, there are 2^n possible subsets. Each number from 0 to 2^n-1 represents a unique combination where each bit indicates whether to include that element.
Using Bit Manipulation
const set = ['x', 'y', 'z'];
const powerSet = (arr = []) => {
const res = [];
const { length } = arr;
const numberOfCombinations = 2 ** length;
for (let combinationIndex = 0; combinationIndex
[
[],
[ 'x' ],
[ 'y' ],
[ 'x', 'y' ],
[ 'z' ],
[ 'x', 'z' ],
[ 'y', 'z' ],
[ 'x', 'y', 'z' ]
]
Using Recursive Approach
const recursivePowerSet = (arr) => {
if (arr.length === 0) {
return [[]];
}
const firstElement = arr[0];
const restElements = arr.slice(1);
const subsetsWithoutFirst = recursivePowerSet(restElements);
const subsetsWithFirst = subsetsWithoutFirst.map(subset =>
[firstElement, ...subset]
);
return [...subsetsWithoutFirst, ...subsetsWithFirst];
};
console.log(recursivePowerSet(['a', 'b']));
[
[],
[ 'b' ],
[ 'a' ],
[ 'a', 'b' ]
]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Bit Manipulation | O(n × 2^n) | O(n × 2^n) | Moderate |
| Recursive | O(n × 2^n) | O(n × 2^n) | High |
Key Points
- A power set always contains 2^n subsets for n elements
- The empty set and the original set are always included
- Bit manipulation provides an efficient iterative solution
- Recursion offers a more intuitive understanding of the problem
Conclusion
Power sets can be generated using bit manipulation for efficiency or recursion for clarity. Both approaches have the same time complexity but the recursive method is more readable and easier to understand.
