Power Set in Lexicographic order in C++

C++Server Side ProgrammingProgramming

In this problem, we are given string str. Our task is to print the power set of this string’s elements in lexicographical order.

Power Set − The power set of a set is the set of all subsets of the set. Denoted by P(S) where s is the set.


S = {1, 2, 3} ;
p(S) = {{}, {1}, {1, 2}, {1, 3}, {2}, {2, 3}, {3}, {1,2,3}}

In this problem, we will treat the string as a set. So, its characters will be the elements of the set.

Let’s take an example to understand the problem

Input − str = “xyz”

Output − x xy xyz xz y yz z

To solve this problem, we will have to sort the array, so that lexicographical order can be obtained. Then we will fix one element of the string and recursively call for the rest elements which will generate all the substring. And discard the first fixed element to obtain the next permutation.


Program to show the implementation of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printAllSubsets(string str, int n, int index = -1, string subset = "") {
   if (index == n)
   for (int i = index + 1; i < n; i++) {
      subset+= str[i];
      printAllSubsets(str, n, i, subset);
      subset = subset.erase(subset.size() - 1);
void GeneratePowerSet(string str) {
   sort(str.begin(), str.end());
   printAllSubsets(str, str.size());
int main() {
   string str = "xyz";
   cout<<"Power Set of the string '"<<str<<"' is :\n";
   return 0;


Power Set of the string 'xyz' is:
x xy xyz xz y yz z
Updated on 17-Apr-2020 06:46:51