![]() |
VOOZH | about |
Power Set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}. If S has n elements in it then P(s) will have 2n elements
Input: s = "ab"
Output: "", "a", "b", "ab"
Explanation: The power set of "ab" includes all possible subsets: empty set, single characters, and full string.Input: s = "abc"
Output: "", "a", "b", "c", "ab", "bc", "ac", "abc"
Explanation: The power set of "abc" includes all subsets formed by choosing any combination of its characters.Input: s = "a"
Output: "", "a"
Explanation: The power set of "a" consists of the empty set and the single character itself.
For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set.
Set = [a,b,c]
power_set_size = pow(2, 3) = 8
Run for binary counter = 000 to 111. We consider a when the last bit is set and do not consider if the last bit is not set. We do the same thing for b and second bit, and for c and first bit.Value of Counter Subset
000 -> Empty set
001 -> a
010 -> b
011 -> ab
100 -> c
101 -> ac
110 -> bc
111 -> abc
Detailed Steps:
a b ab c ac bc abc
Time Complexity: O(n * 2n)
Auxiliary Space: O(1)
We can generate power set using previous permutation. In auxiliary array of bool set all elements to 0. That represent an empty set.
- Set first element of auxiliary array to 1 and generate all permutations to produce all subsets with one element.
- Then set the second element to 1 which will produce all subsets with two elements, repeat until all elements are included.
a b c ab ac bc abc
Time Complexity: O(n * 2n)
Auxiliary Space: O(n)
Related article:
Recursive program to generate power set