Open In App

Power Set

Last Updated : 17 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

Examples

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.

Approach: By Using Binary Representation of Numbers from 0 to 2^n - 1

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:

  • Get the size of power set
    • powet_set_size = pow(2, set_size)
  • Loop for counter from 0 to pow_set_size
    • Loop for i = 0 to set_size
      • If ith bit in counter is set. Print ith element from set for this subset
    • Print separator for subsets i.e., newline
C++
// C++ program to find the power set using
// binary representation of a number.

#include <bits/stdc++.h>
using namespace std;

vector<string> allPossibleStrings(string &s) {
    int n = s.size();
    vector<string> res;

    // Iterate through all subsets (represented by 0 to 2^n - 1)
    for (int i = 0; i < (1 << n); i++) { 
        string sub = "";
        for (int j = 0; j < n; j++) {
       if (i & (1 << j)) sub += s[j];
        }
        res.push_back(sub);  
    }

      
    return res;
}

int main() {
    string s = "abc";
    vector<string> subsets = allPossibleStrings(s);
     for (string sub : subsets) cout << sub << endl;
    return 0;
}
Java
// Java program to find the power set using
// binary representation of a number.

import java.util.ArrayList;
import java.util.List;

class GfG {
    static List<String> AllPossibleStrings(String s)
    {
        int n = s.length();
        List<String> res = new ArrayList<>();

        // Iterate through all subsets (represented by 0 to
        // 2^n - 1)
        for (int i = 0; i < (1 << n); i++) {
            StringBuilder sub = new StringBuilder();
            for (int j = 0; j < n; j++) {
                // Check if the j-th bit is set in i
                if ((i & (1 << j)) != 0) {
                    sub.append(s.charAt(j));
                }
            }
            res.add(sub.toString()); // Add the subset to
                                     // the result
        }

        return res;
    }

    public static void main(String[] args)
    {
        String s = "abc";
        List<String> subsets = AllPossibleStrings(s);

        // Print all subsets
        for (String sub : subsets) {
            System.out.println(sub);
        }
    }
}
Python
# Python program to find the power set using
# binary representation of a number.

def allPossibleStrings(s):
    n = len(s)
    result = []

    # Iterate through all subsets (represented by 0 to 2^n - 1)
    for i in range(1 << n):   
        subset = ""
        for j in range(n):
            # Check if the j-th bit is set in i
            if i & (1 << j):
                subset += s[j]
                
            # Add the subset to the result
        result.append(subset)   

    return result

 
if __name__ == "__main__":
    s = "abc"
    subsets = allPossibleStrings(s)
 
    for subset in subsets:
        print(subset)
C#
// C# program to find the power set using
// binary representation of a number.

using System;
using System.Collections.Generic;

class GfG {
    static List<string> allPossibleStrings(string s) {
        int n = s.Length;
        List<string> result = new List<string>();

        // Iterate through all subsets (represented by 0 to
        // 2^n - 1)
        for (int i = 0; i < (1 << n); i++) {
            string subset = "";
            for (int j = 0; j < n; j++) {
                // Check if the j-th bit is set in i
                if ((i & (1 << j)) != 0) {
                    subset += s[j];
                }
            }
            result.Add(subset);
        }

        return result;
    }

    static void Main(string[] args) {
        string s = "abc";
        List<string> subsets = allPossibleStrings(s);

        foreach(string subset in subsets) {
            Console.WriteLine(subset);
        }
    }
}
JavaScript
// JavaScript program to find the power set using
// binary representation of a number.

function allPossibleStrings(s) {
    const n = s.length;
    const result = [];

    // Iterate through all subsets (represented by 0 to 2^n
    // - 1)
    for (let i = 0; i < (1 << n);
         i++) {  
        let subset = "";
        for (let j = 0; j < n; j++) {
            // Check if the j-th bit is set in i
            if (i & (1 << j)) {
                subset += s[j];
            }
        }
        result.push(subset);  
    }

    return result;
}
 
const s = "abc";
const subsets = allPossibleStrings(s);
subsets.forEach(subset => console.log(subset));

Output
a
b
ab
c
ac
bc
abc

Time Complexity: O(n * 2n)
Auxiliary Space: O(1)

Approach: Power set using Previous Permutation

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.
C++
// C++ program to find the power set using
// prev_permutation

#include <bits/stdc++.h>
using namespace std;

vector<string> allPossibleStrings(string &s) {
    int n = s.size();
    vector<string> res;

    // Initialize a boolean array to represent
    // the inclusion of each character
    // Initially, no character is included
    vector<bool> contain(n, false);

    // Print the empty subset (which is always
    // part of the power set)
    res.push_back("");

    // Loop through all possible combinations of
    // characters
    for (int i = 1; i <= n; i++) {
      
        // Generate the combinations of size 'i'
        // using prev_permutation
        fill(contain.begin(), contain.end(), false);
        for (int j = 0; j < i; j++) {
          
            // Mark the first 'i' elements to be included
            contain[j] = true;
        }
    
        do {
            string subset = "";
            for (int j = 0; j < n; j++) {
                if (contain[j]) {
                  
                    // Add the character to the subset if it's marked
                    subset += s[j];
                }
            }
            // Add the subset to the result
            res.push_back(subset);
        } while (prev_permutation(contain.begin(), contain.end()));
    }

    return res;
}

int main() {
    string s = "abc";
    vector<string> subsets = allPossibleStrings(s);
    for (const string &sub : subsets) {
        cout << sub << endl;
    }
    return 0;
}
Java
// Java program to find the power set using
// prev_permutation

import java.util.*;

class GfG {

    static List<String> allPossibleStrings(String s) {
        int n = s.length();
        List<String> res = new ArrayList<>();

        // Iterate through all subsets (represented by 0 to
        // 2^n - 1)
        for (int i = 0; i < (1 << n); i++) {
            StringBuilder subset = new StringBuilder();
            for (int j = 0; j < n; j++) {
                // If the j-th bit is set in i, include the
                // j-th character from s
                if ((i & (1 << j)) != 0) {
                    subset.append(s.charAt(j));
                }
            }
            res.add(subset.toString());
        }

        return res;
    }
 
    public static void main(String[] args) {
        String s = "abc";
        List<String> subsets = allPossibleStrings(s);
         for (String subset : subsets) {
            System.out.println(subset);
        }
    }
}
Python
# Python program to find the power set using
# prev_permutation'

def allPossibleStrings(s):
    n = len(s)
    result = []

    # Iterate through all subsets (represented 
    # by 0 to 2^n - 1)
    # 1 << n is equivalent to 2^n
    for i in range(1 << n):   
        subset = ""
        for j in range(n):
          
            # If the j-th bit is set in i, include
            # the j-th character from s
            if i & (1 << j):
                subset += s[j]
        result.append(subset)

    return result

 
if __name__ == "__main__":
    s = "abc"
    subsets = allPossibleStrings(s) 
    for subset in subsets:
        print(subset)
C#
// C# program to find the power set using
// prev_permutation

using System;
using System.Collections.Generic;

class GfG {
   
    static List<string> allPossibleStrings(string s) {
        int n = s.Length;
        List<string> result = new List<string>();

        // Iterate through all subsets (represented by 0 to
        // 2^n - 1)
        for (int i = 0; i < (1 << n);
             i++) {
            string subset = "";
            for (int j = 0; j < n; j++) {
              
                // If the j-th bit is set in i, include the
                // j-th character from s
                if ((i & (1 << j)) != 0) {
                    subset += s[j];
                }
            }
            result.Add(subset);
        }

        return result;
    }

    
    static void Main(string[] args) {
        string s = "abc";
        List<string> subsets = allPossibleStrings(s);
 
        foreach(string subset in subsets) {
            Console.WriteLine(subset);
        }
    }
}
JavaScript
// JavaScript program to find the power set using
// prev_permutation

function allPossibleStrings(s) {
    const n = s.length;
    const result = [];

    // Iterate through all subsets (represented by 0 to 2^n
    // - 1)
    for (let i = 0; i < (1 << n);
         i++) {  
        let subset = [];
        for (let j = 0; j < n; j++) {
        
            // If the j-th bit is set in i, include the j-th
            // character from s
            if ((i & (1 << j)) !== 0) {
                subset.push(s[j]);
            }
        }
        result.push(subset.join(""));
    }

    return result;
}

const s = "abc";
const subsets = allPossibleStrings(s);
subsets.forEach(subset => { console.log(subset); });

Output
a
b
c
ab
ac
bc
abc

Time Complexity: O(n * 2n)
Auxiliary Space: O(n)

Related article:
Recursive program to generate power set
 


Power Set | DSA Problem
Article Tags :
Practice Tags :

Similar Reads