Recursive program to generate power set
Last Updated :
11 Jul, 2025
Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order.
Examples:
Input : set = "abc"
Output : { "", "a", "b", "c", "ab", "ac", "bc", "abc"}
Input : set = "abcd"
Output : { "", "a" ,"ab" ,"abc" ,"abcd", "abd" ,"ac" ,"acd", "ad" ,"b", "bc" ,"bcd" ,"bd" ,"c" ,"cd" ,"d" }
Using Pick and Do Not Pick for Every Element:
The idea is to consider two cases for every character.
(i) Consider current character as part of current subset
(ii) Do not consider current character as part of the current subset.
Follow the approach to implement the above idea:
- The base condition of the recursive approach is when the current index reaches the size of the given string (i.e, index == n). then print the current string say, curr.
- Make two recursive calls for the two cases for every character
- We consider the character as part of the current subset
- We do not consider current character as part of the current subset
C++
// CPP program to generate power set
#include <bits/stdc++.h>
using namespace std;
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
void powerSet(string str, int index = 0, string curr = "")
{
int n = str.length();
// base case
if (index == n) {
cout << curr << endl;
return;
}
// Two cases for every character
// (i) We consider the character
// as part of current subset
// (ii) We do not consider current
// character as part of current
// subset
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
// Driver code
int main()
{
string str = "abc";
powerSet(str);
return 0;
}
Java
// Java program to generate power set
class GFG {
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
static void powerSet(String str, int index, String curr)
{
int n = str.length();
// base case
if (index == n) {
System.out.println(curr);
return;
}
// Two cases for every character
// (i) We consider the character
// as part of current subset
// (ii) We do not consider current
// character as part of current
// subset
powerSet(str, index + 1, curr + str.charAt(index));
powerSet(str, index + 1, curr);
}
// Driver code
public static void main(String[] args)
{
String str = "abc";
int index = 0;
String curr = "";
powerSet(str, index, curr);
}
}
// This code is contributed by 29AjayKumar
Python
# Python3 program to generate power set
def powerSet(string, index, curr):
# string : Stores input string
# curr : Stores current subset
# index : Index in current subset, curr
if index == len(string):
print(curr)
return
powerSet(string, index + 1,
curr + string[index])
powerSet(string, index + 1, curr)
# Driver Code
if __name__ == "__main__":
s1 = "abc"
index = 0
curr = ""
powerSet(s1, index, curr)
# This code is contributed by Ekta Singh
C#
// C# program to generate power set
using System;
class GFG {
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
static void powerSet(String str, int index, String curr)
{
int n = str.Length;
// base case
if (index == n) {
Console.WriteLine(curr);
return;
}
// Two cases for every character
// (i) We consider the character
// as part of current subset
// (ii) We do not consider current
// character as part of current
// subset
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
// Driver code
public static void Main()
{
String str = "abc";
int index = 0;
String curr = "";
powerSet(str, index, curr);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to generate power set
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
function powerSet(str,index,curr)
{
let n = str.length;
// base case
if (index == n)
{
document.write(curr+"<br>");
return;
}
// Two cases for every character
// (i) We consider the character
// as part of current subset
// (ii) We do not consider current
// character as part of current
// subset
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
// Driver code
let str = "abc";
let index = 0;
let curr="";
powerSet(str,index,curr);
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
Fixing Prefixes One by One
The idea is to fix a prefix, and generate all subsets beginning with the current prefix. After all subsets with a prefix are generated, replace the last character with one of the remaining characters.
Follow the approach to implement the above idea:
- The base condition of the recursive approach is when the current index reaches the size of the given string (i.e, index == n), then return
- First, print the current subset
- Iterate over the given string from the current index (i.e, index) to less than the size of the string
- Appending the remaining characters to the current subset
- Make the recursive call for the next index.
- Once all subsets beginning with the initial "curr" are printed, remove the last character to consider a different prefix of subsets.
Follow the steps below to implement the above approach:
C++
// CPP program to generate power set
#include <bits/stdc++.h>
using namespace std;
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
void powerSet(string str, int index = -1, string curr = "")
{
int n = str.length();
// base case
if (index == n)
return;
// First print current subset
cout << curr << "\n";
// Try appending remaining characters
// to current subset
for (int i = index + 1; i < n; i++) {
curr += str[i];
powerSet(str, i, curr);
// Once all subsets beginning with
// initial "curr" are printed, remove
// last character to consider a different
// prefix of subsets.
curr.erase(curr.size() - 1);
}
return;
}
// Driver code
int main()
{
string str = "abc";
powerSet(str);
return 0;
}
Java
// Java program to generate power set
import java.util.*;
class GFG {
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
static void powerSet(String str, int index, String curr)
{
int n = str.length();
// base case
if (index == n) {
return;
}
// First print current subset
System.out.println(curr);
// Try appending remaining characters
// to current subset
for (int i = index + 1; i < n; i++) {
curr += str.charAt(i);
powerSet(str, i, curr);
// Once all subsets beginning with
// initial "curr" are printed, remove
// last character to consider a different
// prefix of subsets.
curr = curr.substring(0, curr.length() - 1);
}
}
// Driver code
public static void main(String[] args)
{
String str = "abc";
int index = -1;
String curr = "";
powerSet(str, index, curr);
}
}
// This code is contributed by PrinciRaj1992
Python
# Python3 program to generate power set
# str : Stores input string
# curr : Stores current subset
# index : Index in current subset, curr
def powerSet(str1, index, curr):
n = len(str1)
# base case
if (index == n):
return
# First print current subset
print(curr)
# Try appending remaining characters
# to current subset
for i in range(index + 1, n):
curr += str1[i]
powerSet(str1, i, curr)
# Once all subsets beginning with
# initial "curr" are printed, remove
# last character to consider a different
# prefix of subsets.
curr = curr.replace(curr[len(curr) - 1], "")
return
# Driver code
if __name__ == '__main__':
str = "abc"
powerSet(str, -1, "")
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to generate power set
using System;
class GFG {
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
static void powerSet(string str, int index, string curr)
{
int n = str.Length;
// base case
if (index == n) {
return;
}
// First print current subset
Console.WriteLine(curr);
// Try appending remaining characters
// to current subset
for (int i = index + 1; i < n; i++) {
curr += str[i];
powerSet(str, i, curr);
// Once all subsets beginning with
// initial "curr" are printed, remove
// last character to consider a different
// prefix of subsets.
curr = curr.Substring(0, curr.Length - 1);
}
}
// Driver code
public static void Main()
{
string str = "abc";
int index = -1;
string curr = "";
powerSet(str, index, curr);
}
}
// This code is contributed by Ita_c.
JavaScript
<script>
// Javascript program to generate power set
// str : Stores input string
// curr : Stores current subset
// index : Index in current subset, curr
function powerSet(str,index,curr)
{
let n = str.length;
// base case
if (index == n)
{
return;
}
// First print current subset
document.write(curr+"<br>");
// Try appending remaining characters
// to current subset
for (let i = index + 1; i < n; i++)
{
curr += str[i];
powerSet(str, i, curr);
// Once all subsets beginning with
// initial "curr" are printed, remove
// last character to consider a different
// prefix of subsets.
curr = curr.substring(0, curr.length - 1);
}
}
// Driver code
let str = "abc";
let index = -1;
let curr = "";
powerSet(str, index, curr);
// This code is contributed by rag2127
</script>
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
Using Bottom Up Approach
The idea is to pick each element one by one from the input set, then generate a subset for the same, and we follow this process recursively.
Follow the steps below to implement the above idea:
- The base condition for the recursive call, when the current index becomes negative then add empty list into the allSubsets.
- Make recursive call for the current index - 1, then we'll receive allSubsets list from 0 to index -1
- Create a list of list moreSubsets
- Iterate over all the subsets that are received from above recursive call
- Copy all the subset into newSubset
- Add the current item into newSubset
- Add newSubset into moreSubsets
- Add moreSubsets into allSubsets
- Finally, return allSubsets.
Follow the steps below to implement the above approach:
C++
// C++ Recursive code to print
// all subsets of set using ArrayList
#include <bits/stdc++.h>
using namespace std;
vector<vector<string> > getSubset(vector<string> set,
int index)
{
vector<vector<string> > allSubsets;
if (index < 0) {
vector<string> v;
allSubsets.push_back(v);
}
else {
allSubsets = getSubset(set, index - 1);
string item = set[index];
vector<vector<string> > moreSubsets;
for (vector<string> subset : allSubsets) {
vector<string> newSubset;
for (auto it : subset)
newSubset.push_back(it);
newSubset.push_back(item);
moreSubsets.push_back(newSubset);
}
for (auto it : moreSubsets)
allSubsets.push_back(it);
}
return allSubsets;
}
int main()
{
vector<string> set = { "a", "b", "c" };
int index = set.size() - 1;
vector<vector<string> > result = getSubset(set, index);
for (auto it : result) {
cout << " [ ";
for (auto itr : it) {
cout << itr << ",";
}
cout << "],";
}
}
// This code is contributed by garg28harsh.
Java
// Java Recursive code to print
// all subsets of set using ArrayList
import java.util.ArrayList;
public class PowerSet {
public static void main(String[] args)
{
String[] set = { "a", "b", "c" };
int index = set.length - 1;
ArrayList<ArrayList<String> > result
= getSubset(set, index);
System.out.println(result);
}
static ArrayList<ArrayList<String> >
getSubset(String[] set, int index)
{
ArrayList<ArrayList<String> > allSubsets;
if (index < 0) {
allSubsets
= new ArrayList<ArrayList<String> >();
allSubsets.add(new ArrayList<String>());
}
else {
allSubsets = getSubset(set, index - 1);
String item = set[index];
ArrayList<ArrayList<String> > moreSubsets
= new ArrayList<ArrayList<String> >();
for (ArrayList<String> subset : allSubsets) {
ArrayList<String> newSubset
= new ArrayList<String>();
newSubset.addAll(subset);
newSubset.add(item);
moreSubsets.add(newSubset);
}
allSubsets.addAll(moreSubsets);
}
return allSubsets;
}
}
Python
# Python recursive code to print
# all subsets of set using ArrayList
def get_subset(s, index):
all_subsets = []
if index < 0:
all_subsets.append([])
else:
all_subsets = get_subset(s, index-1)
item = s[index]
more_subsets = []
for subset in all_subsets:
new_subset = []
for i in subset:
new_subset.append(i)
new_subset.append(item)
more_subsets.append(new_subset)
for i in more_subsets:
all_subsets.append(i)
return all_subsets
# Driver Code
set = ["a", "b", "c"]
index = len(set) - 1
result = get_subset(set, index)
for subset in result:
print("[", end=" ")
for item in subset:
print(item, end=" ")
print("],", end=" ")
C#
// c# code for the above approach
using System;
using System.Collections.Generic;
namespace Subsets {
public class GFG {
static List<List<string> > GetSubsets(List<string> set,
int index)
{
List<List<string> > allSubsets;
if (index < 0) {
List<string> emptyList = new List<string>();
allSubsets
= new List<List<string> >{ emptyList };
}
else {
allSubsets = GetSubsets(set, index - 1);
string item = set[index];
List<List<string> > moreSubsets
= new List<List<string> >();
foreach(List<string> subset in allSubsets)
{
List<string> newSubset = new List<string>();
foreach(string it in subset)
{
newSubset.Add(it);
}
newSubset.Add(item);
moreSubsets.Add(newSubset);
}
foreach(List<string> it in moreSubsets)
{
allSubsets.Add(it);
}
}
return allSubsets;
}
static void Main(string[] args)
{
List<string> set
= new List<string>{ "a", "b", "c" };
int index = set.Count - 1;
List<List<string> > result = GetSubsets(set, index);
foreach(List<string> it in result)
{
Console.Write("[ ");
foreach(string itr in it)
{
Console.Write(itr + " ");
}
Console.Write("], ");
}
}
}
}
JavaScript
//javascript code for the above approach
function getSubset(set, index) {
let allSubsets = [];
if (index < 0) {
let v = [];
allSubsets.push(v);
} else {
allSubsets = getSubset(set, index - 1);
let item = set[index];
let moreSubsets = [];
for (let subset of allSubsets) {
let newSubset = [];
for (let it of subset)
newSubset.push(it);
newSubset.push(item);
moreSubsets.push(newSubset);
}
for (let it of moreSubsets)
allSubsets.push(it);
}
return allSubsets;
}
let set = ["a", "b", "c"];
let index = set.length - 1;
let result = getSubset(set, index);
for (let it of result) {
console.log(" [ " + it.join(",") + " ],");
}
Output[[], [a], [b], [a, b], [c][/c], [a, c], [b, c], [a, b, c]]
Time Complexity: O(n*2n)
Auxiliary Space: O(n), For recursive call stack
Iterative program for the power set.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem