All possible strings of any length that can be formed from a given string
Last Updated :
02 Oct, 2023
Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples:
Input: abc
Output: a b c abc ab ac bc bac bca
cb ca ba cab cba acb
Input: abcd
Output: a b ab ba c ac ca bc cb abc acb bac
bca cab cba d ad da bd db abd adb bad
bda dab dba cd dc acd adc cad cda dac
dca bcd bdc cbd cdb dbc dcb abcd abdc
acbd acdb adbc adcb bacd badc bcad bcda
bdac bdca cabd cadb cbad cbda cdab cdba
dabc dacb dbac dbca dcab dcba
Approach 1:
The generation of all strings include the following steps.
1) Generate all subsequences of given string.
2) For every subsequence ‘subs’, print all permutations of ‘subs’
Below is C++ implementation. It uses next_permutation function in C++.
C++
#include<bits/stdc++.h>
using namespace std;
void printAll(string str)
{
int n = str.length();
unsigned int opsize = pow (2, n);
for ( int counter = 1; counter < opsize; counter++)
{
string subs = "" ;
for ( int j = 0; j < n; j++)
{
if (counter & (1<<j))
subs.push_back(str[j]);
}
do
{
cout << subs << " " ;
}
while (next_permutation(subs.begin(), subs.end()));
}
}
int main()
{
string str = "abc" ;
printAll(str);
return 0;
}
|
Java
import java.util.*;
class Main {
static void printAll(String str) {
int n = str.length();
int opsize = ( int )Math.pow( 2 , n);
for ( int counter = 1 ; counter < opsize; counter++) {
StringBuilder subs = new StringBuilder();
for ( int j = 0 ; j < n; j++) {
if ((counter & ( 1 << j)) != 0 )
subs.append(str.charAt(j));
}
char [] chars = subs.toString().toCharArray();
Arrays.sort(chars);
do {
System.out.print(String.valueOf(chars) + " " );
} while (nextPermutation(chars));
}
}
static boolean nextPermutation( char [] arr) {
int i = arr.length - 2 ;
while (i >= 0 && arr[i] >= arr[i + 1 ])
i--;
if (i < 0 )
return false ;
int j = arr.length - 1 ;
while (arr[j] <= arr[i])
j--;
swap(arr, i, j);
reverse(arr, i + 1 , arr.length - 1 );
return true ;
}
static void swap( char [] arr, int i, int j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void reverse( char [] arr, int i, int j) {
while (i < j)
swap(arr, i++, j--);
}
public static void main(String[] args) {
String str = "abc" ;
printAll(str);
}
}
|
Python3
from itertools import permutations
def printAll( st):
n = len (st)
opsize = pow ( 2 , n)
for counter in range ( 1 , opsize):
subs = ""
for j in range (n):
if (counter & ( 1 <<j)):
subs + = (st[j])
perm = permutations(subs)
for i in perm:
print (''.join(i),end = " " )
if __name__ = = "__main__" :
st = "abc"
printAll((st))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class MainClass {
static void printAll( string str)
{
int n = str.Length;
int opsize = ( int )Math.Pow(2, n);
for ( int counter = 1; counter < opsize; counter++) {
var subs = new StringBuilder();
for ( int j = 0; j < n; j++) {
if ((counter & (1 << j)) != 0)
subs.Append(str[j]);
}
char [] chars = subs.ToString().ToCharArray();
Array.Sort(chars);
do {
Console.Write( new string (chars) + " " );
} while (nextPermutation(chars));
}
}
static bool nextPermutation( char [] arr)
{
int i = arr.Length - 2;
while (i >= 0 && arr[i] >= arr[i + 1])
i--;
if (i < 0)
return false ;
int j = arr.Length - 1;
while (arr[j] <= arr[i])
j--;
swap(arr, i, j);
reverse(arr, i + 1, arr.Length - 1);
return true ;
}
static void swap( char [] arr, int i, int j)
{
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void reverse( char [] arr, int i, int j)
{
while (i < j)
swap(arr, i++, j--);
}
public static void Main( string [] args)
{
string str = "abc" ;
printAll(str);
}
}
|
Javascript
function printAll(str) {
const n = str.length;
const opsize = 2 ** n;
ans = ""
for (let counter = 1; counter < opsize; counter++) {
let subs = "" ;
for (let j = 0; j < n; j++) {
if ((counter & (1 << j)) != 0) {
subs += str.charAt(j);
}
}
const chars = subs.split( "" ).sort();
do {
ans = ans + chars.join( "" ) + " " ;
} while (nextPermutation(chars));
} console.log(ans);
}
function nextPermutation(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false ;
}
let j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
swap(arr, i, j);
reverse(arr, i + 1, arr.length - 1);
return true ;
}
function swap(arr, i, j) {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function reverse(arr, i, j) {
while (i < j) {
swap(arr, i++, j--);
}
}
const str = "abc" ;
printAll(str);
|
Output
a b ab ba c ac ca bc cb abc acb bac bca cab cba
Time complexity: O(n * 2^n * n!)
Auxiliary Space : O(2^n * n)
Approach 2 :
- Generate all possible combinations of the given string using a bitmask.
- For each combination, generate all possible permutations of the characters in that combination.
- Print each permutation.
Below is the code for the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void printAll(string str)
{
int n = str.length();
int combos = (1 << n);
for ( int i=1; i<combos; i++)
{
string curr_combination = "" ;
for ( int j=0; j<n; j++)
{
if (i & (1 << j))
curr_combination.push_back(str[j]);
}
sort(curr_combination.begin(), curr_combination.end());
do {
cout << curr_combination << " " ;
} while (next_permutation(curr_combination.begin(), curr_combination.end()));
}
}
int main()
{
string str = "abc" ;
printAll(str);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static void printAll(String str) {
int n = str.length();
int combos = ( 1 << n);
for ( int i = 1 ; i < combos; i++) {
StringBuilder curr_combination = new StringBuilder();
for ( int j = 0 ; j < n; j++) {
if ((i & ( 1 << j)) != 0 )
curr_combination.append(str.charAt(j));
}
char [] curr_combination_chars = curr_combination.toString().toCharArray();
Arrays.sort(curr_combination_chars);
do {
System.out.print( new String(curr_combination_chars) + " " );
} while (nextPermutation(curr_combination_chars));
}
}
static boolean nextPermutation( char [] arr) {
int i = arr.length - 2 ;
while (i >= 0 && arr[i] >= arr[i + 1 ])
i--;
if (i < 0 )
return false ;
int j = arr.length - 1 ;
while (arr[j] <= arr[i])
j--;
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Arrays.sort(arr, i + 1 , arr.length);
return true ;
}
public static void main(String[] args) {
String str = "abc" ;
printAll(str);
}
}
|
Python3
def print_all( str ):
n = len ( str )
combos = ( 1 << n)
for i in range ( 1 , combos):
curr_combination = ""
for j in range (n):
if i & ( 1 << j):
curr_combination + = str [j]
curr_combination = sorted (curr_combination)
from itertools import permutations
for perm in permutations(curr_combination):
print (" ".join(perm), end=" ")
def main():
str = "abc"
print_all( str )
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main( string [] args)
{
string str = "abc" ;
PrintAll(str);
}
static void PrintAll( string str)
{
int n = str.Length;
int combos = (1 << n);
for ( int i = 1; i < combos; i++)
{
List< char > currCombination = new List< char >();
for ( int j = 0; j < n; j++)
{
if ((i & (1 << j)) != 0)
currCombination.Add(str[j]);
}
currCombination.Sort();
GeneratePermutations(currCombination, 0);
}
}
static void GeneratePermutations(List< char > combination, int startIndex)
{
if (startIndex == combination.Count)
{
Console.Write( new string (combination.ToArray()) + " " );
return ;
}
for ( int i = startIndex; i < combination.Count; i++)
{
Swap(combination, startIndex, i);
GeneratePermutations(combination, startIndex + 1);
Swap(combination, startIndex, i);
}
}
static void Swap(List< char > list, int i, int j)
{
char temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
|
Javascript
function printAll(str) {
const n = str.length;
const combos = 1 << n;
for (let i = 1; i < combos; i++) {
let curr_combination = "" ;
for (let j = 0; j < n; j++) {
if (i & (1 << j))
curr_combination += str[j];
}
curr_combination = curr_combination.split( '' );
curr_combination.sort();
do {
console.log(curr_combination.join( ' ' ) + ' ' );
} while (nextPermutation(curr_combination));
}
}
function nextPermutation(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false ;
}
let j = arr.length - 1;
while (j > i && arr[j] <= arr[i]) {
j--;
}
[arr[i], arr[j]] = [arr[j], arr[i]];
reverse(arr, i + 1);
return true ;
}
function reverse(arr, start) {
let end = arr.length - 1;
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
}
const str = "abc" ;
printAll(str);
|
Output
a b ab ba c ac ca bc cb abc acb bac bca cab cba
Time complexity : O(n * 2^n * n!)
Auxiliary Space : O(n)
Share your thoughts in the comments
Please Login to comment...