Power Set

Last Updated : 23 Oct, 2026

Given a string s containing lowercase English letters, generate and return the power set of the string. The power set contains all possible subsets of the characters in s, including the empty string and the string itself. The subsets can be returned in any order.

Examples

Input: s = "ab"
Output: ["", "a", "b", "ab"]
Explanation: The power set contains the empty string, the single-character subsets "a" and "b", and the complete string "ab".

Input: s = "abc"
Output: ["", "a", "b", "c", "ab", "ac", "bc", "abc"]
Explanation: All eight subsets are formed by choosing different combinations of the three characters.

Input: s = "a"
Output: ["", "a"]
Explanation: The power set contains the empty string and the string "a" itself.

Try It Yourself
redirect icon

Pick and Not Pick Recursion - O(n*2^n) Time and O(n) Space

For each character in the string, consider two choices:

  • Either include the character in the current subset
  • Or exclude it.

Recursively explore both choices. When all characters have been processed, add the current subset to the result.

  • Start with an empty subset and index 0.
  • If the index reaches the length of the string, add the current subset to the result.
  • Recursively explore the choice of including the current character.
  • Recursively explore the choice of excluding the current character.
  • Continue until all possible subsets have been generated.
frame_1000002006
C++
#include <bits/stdc++.h>
using namespace std;

void generateSubsets(string &s, int index, string curr, vector<string> &res)
{
    int n = s.length();

    // Base case
    if (index == n)
    {
        res.push_back(curr);
        return;
    }

    // Include the current character
    generateSubsets(s, index + 1, curr + s[index], res);

    // Exclude the current character
    generateSubsets(s, index + 1, curr, res);
}

vector<string> powerSet(string s)
{
    vector<string> res;
    generateSubsets(s, 0, "", res);

    return res;
}

int main()
{
    string s = "abc";
    vector<string> res = powerSet(s);

    // Sort subsets by length, then lexicographically
    sort(res.begin(), res.end(), [](string a, string b) {
        if (a.length() != b.length())
            return a.length() < b.length();
        return a < b;
    });

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]" << endl;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    // Function to generate all subsets of the given string
    static void generateSubsets(String s, int index,
                                String curr,
                                ArrayList<String> res)
    {
        int n = s.length();

        // Base case
        if (index == n) {
            res.add(curr);
            return;
        }

        // Include the current character
        generateSubsets(s, index + 1,
                        curr + s.charAt(index), res);

        // Exclude the current character
        generateSubsets(s, index + 1, curr, res);
    }

    static ArrayList<String> powerSet(String s)
    {
        ArrayList<String> res = new ArrayList<>();
        generateSubsets(s, 0, "", res);
        return res;
    }

    public static void main(String[] args)
    {
        String s = "abc";
        ArrayList<String> res = powerSet(s);

        // Sort subsets by length, then lexicographically
        res.sort((a, b) -> {
            if (a.length() != b.length())
                return a.length() - b.length();
            return a.compareTo(b);
        });

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i != res.size() - 1)
                System.out.print(", ");
        }
        System.out.println("]");
    }
}
Python
def generateSubsets(s, index, curr, res):
    n = len(s)

    # Base case
    if index == n:
        res.append(curr)
        return

    # Include the current character
    generateSubsets(s, index + 1, curr + s[index], res)

    # Exclude the current character
    generateSubsets(s, index + 1, curr, res)


def powerSet(s):
    res = []
    generateSubsets(s, 0, "", res)
    return res


if __name__ == '__main__':
    s = "abc"
res = powerSet(s)

# Sort subsets by length, then lexicographically
res.sort(key=lambda a: (len(a), a))

print("[" + ", ".join('"' + x + '"' for x in res) + "]")
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to generate all subsets of the given string
    static void generateSubsets(string s, int index,
                                string curr,
                                List<string> res)
    {
        int n = s.Length;

        // Base case
        if (index == n) {
            res.Add(curr);
            return;
        }

        // Include the current character
        generateSubsets(s, index + 1, curr + s[index], res);

        // Exclude the current character
        generateSubsets(s, index + 1, curr, res);
    }

    static List<string> powerSet(string s)
    {
        List<string> res = new List<string>();
        generateSubsets(s, 0, "", res);
        return res;
    }

    static void Main()
    {
        string s = "abc";
        List<string> res = powerSet(s);

        // Sort subsets by length, then lexicographically
        res.Sort((a, b) => {
            if (a.Length != b.Length)
                return a.Length.CompareTo(b.Length);
            return string.CompareOrdinal(a, b);
        });

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}
JavaScript
function generateSubsets(s, index, curr, res) {
    const n = s.length;

    // Base case
    if (index === n) {
        res.push(curr);
        return;
    }

    // Include the current character
    generateSubsets(s, index + 1, curr + s[index], res);

    // Exclude the current character
    generateSubsets(s, index + 1, curr, res);
}

function powerSet(s) {
    const res = [];
    generateSubsets(s, 0, "", res);
    return res;
}

// Driver code
const s = "abc";
const res = powerSet(s);

// Sort subsets by length, then lexicographically
res.sort((a, b) => a.length - b.length || a.localeCompare(b));

console.log("[" + res.map(x => JSON.stringify(x)).join(", ") + "]");

Output
["", "a", "b", "c", "ab", "ac", "bc", "abc"]

Recursion and Backtracking - O(n*2^n) Time and O(n) Space

The idea is to generate subsets by adding one character at a time. Recursively append each remaining character to the current subset.

After each recursive call, remove the last character to explore other possibilities.

  • Start with an empty string curr and set index = -1.
  • Add curr to the result.
  • Traverse the string from index index + 1 to n - 1.
  • Append s[i] to curr and recursively generate subsets by calling generateSubsets(s, i, curr, res).
  • Remove the last character to backtrack and try the next character.
C++
#include <bits/stdc++.h>
using namespace std;

void generateSubsets(string &s, int index, string curr,
                     vector<string> &res) {
    int n = s.length();

    // Add the current subset
    res.push_back(curr);

    // Try appending each remaining character
    for (int i = index + 1; i < n; i++) {
        curr += s[i];

        // Generate subsets with the current character
        generateSubsets(s, i, curr, res);

        // Backtrack by removing the last character
        curr.pop_back();
    }
}

vector<string> powerSet(string &s) {
    vector<string> res;
    generateSubsets(s, -1, "", res);
    return res;
}

int main() {
    string s = "abc";
    vector<string> res = powerSet(s);

    cout << "[";
    for (int i = 0; i < res.size(); i++) {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]" << endl;

    return 0;
}
Java
import java.util.ArrayList;

public class GFG {
    public static void generateSubsets(String s, int index, String curr, ArrayList<String> res) {
        int n = s.length();

        // Add the current subset
        res.add(curr);

        // Try appending each remaining character
        for (int i = index + 1; i < n; i++) {
            curr += s.charAt(i);

            // Generate subsets with the current character
            generateSubsets(s, i, curr, res);

            // Backtrack by removing the last character
            curr = curr.substring(0, curr.length() - 1);
        }
    }

    public static ArrayList<String> powerSet(String s) {
        ArrayList<String> res = new ArrayList<>();
        generateSubsets(s, -1, "", res);
        return res;
    }

    public static void main(String[] args) {
        String s = "abc";
        ArrayList<String> res = powerSet(s);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i!= res.size() - 1)
                System.out.print(", ");
        }
        System.out.println("]");
    }
}
Python
def generateSubsets(s, index, curr, res):
    n = len(s)

    # Add the current subset
    res.append(curr)

    # Try appending each remaining character
    for i in range(index + 1, n):
        curr += s[i]

        # Generate subsets with the current character
        generateSubsets(s, i, curr, res)

        # Backtrack by removing the last character
        curr = curr[:-1]

def powerSet(s):
    res = []
    generateSubsets(s, -1, "", res)
    return res

if __name__ == "__main__":
    s = "abc"
    res = powerSet(s)

    print('[', end='')
    for i in range(len(res)):
        print(f'"{res[i]}"', end='')
        if i!= len(res) - 1:
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static void generateSubsets(string s, int index,
                                       string curr,
                                       List<string> res)
    {
        int n = s.Length;

        // Add the current subset
        res.Add(curr);

        // Try appending each remaining character
        for (int i = index + 1; i < n; i++) {
            curr += s[i];

            // Generate subsets with the current character
            generateSubsets(s, i, curr, res);

            // Backtrack by removing the last character
            curr = curr.Substring(0, curr.Length - 1);
        }
    }

    public static List<string> powerSet(string s)
    {
        List<string> res = new List<string>();
        generateSubsets(s, -1, "", res);
        return res;
    }

    public static void Main()
    {
        string s = "abc";
        List<string> res = powerSet(s);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}
JavaScript
function generateSubsets(s, index, curr, res) {
    const n = s.length;

    // Add the current subset
    res.push(curr);

    // Try appending each remaining character
    for (let i = index + 1; i < n; i++) {
        curr += s[i];

        // Generate subsets with the current character
        generateSubsets(s, i, curr, res);

        // Backtrack by removing the last character
        curr = curr.slice(0, -1);
    }
}

function powerSet(s) {
    const res = [];
    generateSubsets(s, -1, "", res);
    return res;
}

// Driver code
    const s = "abc";
    const res = powerSet(s);

    console.log('[');
    for (let i = 0; i < res.length; i++) {
        process.stdout.write(`\"${res[i]}\"`);
        if (i!== res.length - 1) {
            process.stdout.write(', ');
        }
    }
    console.log(']');

Output
["", "a", "ab", "abc", "ac", "b", "bc", "c"]

Incremental Iteration - O(n*2^n) Time and O(n) Space

Start with an empty subset. Process each character of the string and add it to every existing subset to generate new subsets.

  • Initialize the result with an empty string "".
  • Traverse each character of the string.
  • For each character, create new subsets by appending it to every existing subset.
  • Add the newly generated subsets to the result.
  • Return the result after processing all characters.
C++
#include <bits/stdc++.h>
using namespace std;

vector<string> powerSet(string &s) {
    vector<string> res = {""};

    for (char ch : s) {
        int n = res.size();

        for (int i = 0; i < n; i++) {
            res.push_back(res[i] + ch);
        }
    }

    return res;
}

int main() {
    string s = "abc";
    vector<string> res = powerSet(s);

    cout << "[";
    for (int i = 0; i < res.size(); i++) {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]" << endl;

    return 0;
}
Java
import java.util.ArrayList;

public class GFG {
    public static ArrayList<String> powerSet(String s) {
        ArrayList<String> res = new ArrayList<>();
        res.add("");

        for (char ch : s.toCharArray()) {
            int n = res.size();

            for (int i = 0; i < n; i++) {
                res.add(res.get(i) + ch);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        String s = "abc";
        ArrayList<String> res = powerSet(s);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i!= res.size() - 1)
                System.out.print(", ");
        }
        System.out.println("]");
    }
}
Python
def powerSet(s):
    res = [""]

    for ch in s:
        n = len(res)

        for i in range(n):
            res.append(res[i] + ch)

    return res


if __name__ == '__main__':
    s = "abc"
    res = powerSet(s)

    print('[', end='')
    for i in range(len(res)):
        print(f'"{res[i]}"', end='')
        if i!= len(res) - 1:
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static List<string> powerSet(string s) {
        List<string> res = new List<string> { "" };

        foreach (char ch in s) {
            int n = res.Count;

            for (int i = 0; i < n; i++) {
                res.Add(res[i] + ch);
            }
        }

        return res;
    }

    public static void Main() {
        string s = "abc";
        List<string> res = powerSet(s);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i!= res.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}
JavaScript
function powerSet(s) {
    let res = [""];

    for (let ch of s) {
        let n = res.length;

        for (let i = 0; i < n; i++) {
            res.push(res[i] + ch);
        }
    }

    return res;
}

// Driver code
let s = "abc";
let res = powerSet(s);

console.log('[' + res.join('","') + ']');

Output
["", "a", "b", "ab", "c", "ac", "bc", "abc"]

Bitmasking - O(n*2^n)Time and O(n) Space

A string of length n has 2^n possible subsets. Represent each subset using an n-bit number, where each bit indicates whether the corresponding character is included in the subset. If a bit is set, include that character; otherwise, skip it.

  • Calculate the total number of subsets as 1 << n, which is equal to 2^n.
  • Traverse all numbers from 0 to (1 << n) - 1, where each number represents a subset.
  • For each number, initialize an empty string curr and check each bit from 0 to n - 1.
  • Use mask & (1 << i) to check whether the i-th bit is set. If the result is non-zero, include s[i] in the current subset; otherwise, skip it.
  • Add the generated subset to the result.
  • Return the result containing all possible subsets.
bit_representation_of_subset
C++
#include <bits/stdc++.h>
using namespace std;

vector<string> powerSet(string &s) {
    int n = s.length();
    int total = 1 << n;

    vector<string> res;

    for (int mask = 0; mask < total; mask++) {
        string curr = "";

        for (int i = 0; i < n; i++) {
            // Check whether the i-th bit is set
            if (mask & (1 << i)) {
                curr += s[i];
            }
        }

        res.push_back(curr);
    }

    return res;
}

int main() {
    string s = "abc";
    vector<string> res = powerSet(s);

    cout << "[";
    for (int i = 0; i < res.size(); i++) {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]" << endl;

    return 0;
}
Java
import java.util.ArrayList;

public class Main {
    public static ArrayList<String> powerSet(String s) {
        int n = s.length();
        int total = 1 << n;

        ArrayList<String> res = new ArrayList<>();

        for (int mask = 0; mask < total; mask++) {
            StringBuilder curr = new StringBuilder();

            for (int i = 0; i < n; i++) {
                // Check whether the i-th bit is set
                if ((mask & (1 << i))!= 0) {
                    curr.append(s.charAt(i));
                }
            }

            res.add(curr.toString());
        }

        return res;
    }

    public static void main(String[] args) {
        String s = "abc";
        ArrayList<String> res = powerSet(s);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i!= res.size() - 1)
                System.out.print(", ");
        }
        System.out.println("]");
    }
}
Python
def powerSet(s):
    n = len(s)
    total = 1 << n

    res = []

    for mask in range(total):
        curr = ""

        for i in range(n):
            # Check whether the i-th bit is set
            if mask & (1 << i):
                curr += s[i]

        res.append(curr)

    return res


s = "abc"
res = powerSet(s)

print('[' + ', '.join(f'"{item}"' for item in res) + ']')
C#
using System;
using System.Collections.Generic;

public class GFG
{
    public static List<string> powerSet(string s)
    {
        int n = s.Length;
        int total = 1 << n;

        List<string> res = new List<string>();

        for (int mask = 0; mask < total; mask++)
        {
            string curr = "";

            for (int i = 0; i < n; i++)
            {
                // Check whether the i-th bit is set
                if ((mask & (1 << i))!= 0)
                {
                    curr += s[i];
                }
            }

            res.Add(curr);
        }

        return res;
    }

    public static void Main()
    {
        string s = "abc";
        List<string> res = powerSet(s);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++)
        {
            Console.Write("\"" + res[i] + "\"");
            if (i!= res.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}
JavaScript
function powerSet(s) {
    const n = s.length;
    const total = 1 << n;

    const res = [];

    for (let mask = 0; mask < total; mask++) {
        let curr = "";

        for (let i = 0; i < n; i++) {
            // Check whether the i-th bit is set
            if (mask & (1 << i)) {
                curr += s[i];
            }
        }

        res.push(curr);
    }

    return res;
}

// Driver code
const s = 'abc';
const res = powerSet(s);

console.log('[' + res.map(item => '"' + item + '"').join(', ') + ']');

Output
["", "a", "b", "ab", "c", "ac", "bc", "abc"]
Comment