Open In App

All possible strings of any length that can be formed from a given string

Last Updated : 02 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




/*  C++ code to generate all possible strings
    that can be formed from given string */
#include<bits/stdc++.h>
using namespace std;
 
void printAll(string str)
{
    /* Number of subsequences is (2**n -1)*/
    int n = str.length();
    unsigned int opsize = pow(2, n);
 
    /* Generate all subsequences of a given string.
       using counter 000..1 to 111..1*/
    for (int counter = 1; counter < opsize; counter++)
    {
        string subs = "";
        for (int j = 0; j < n; j++)
        {
            /* Check if jth bit in the counter is set
                If set then print jth element from arr[] */
            if (counter & (1<<j))
                subs.push_back(str[j]);
        }
 
        /* Print all permutations of current subsequence */
        do
        {
            cout << subs << " ";
        }
        while (next_permutation(subs.begin(), subs.end()));
    }
}
 
// Driver program
int main()
{
    string str = "abc";
    printAll(str);
    return 0;
}


Java




import java.util.*;
 
class Main {
    static void printAll(String str) {
        /* Number of subsequences is (2**n -1)*/
        int n = str.length();
        int opsize = (int)Math.pow(2, n);
 
        /* Generate all subsequences of a given string.
           using counter 000..1 to 111..1*/
        for (int counter = 1; counter < opsize; counter++) {
            StringBuilder subs = new StringBuilder();
            for (int j = 0; j < n; j++) {
                /* Check if jth bit in the counter is set
                    If set then print jth element from arr[] */
                if ((counter & (1 << j)) != 0)
                    subs.append(str.charAt(j));
            }
 
            /* Print all permutations of current subsequence */
            char[] chars = subs.toString().toCharArray();
            Arrays.sort(chars);
            do {
                System.out.print(String.valueOf(chars) + " ");
            } while (nextPermutation(chars));
        }
    }
   // next permutation function
    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 function
        swap(arr, i, j);
      // Reversing
        reverse(arr, i + 1, arr.length - 1);
        return true;
    }
   // Swap function
    static void swap(char[] arr, int i, int j) {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 // Reverse function
    static void reverse(char[] arr, int i, int j) {
        while (i < j)
            swap(arr, i++, j--);
    }
 
    // Driver program
    public static void main(String[] args) {
        String str = "abc";
        printAll(str);
    }
}


Python3




# Python3 code to generate all possible strings
# that can be formed from given string
from itertools import permutations
   
def printAll( st):
     
    # Number of subsequences is (2**n -1)
    n = len(st)
    opsize = pow(2, n)
  
    # Generate all subsequences of a given string.
    #  using counter 000..1 to 111..1
    for counter in range(1, opsize):
     
        subs = ""
        for j in range(n):
         
            # Check if jth bit in the counter is set
            #   If set then print jth element from arr[]
            if (counter & (1<<j)):
                subs += (st[j])
  
        # Print all permutations of current subsequence
        perm = permutations(subs)
         
        for i in perm:
            print(''.join(i),end=" ")
             
# Driver program
if __name__ == "__main__":
     
    st = "abc"
    printAll((st))
     
# This code is contributed by chitranayal


C#




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
class MainClass {
    static void printAll(string str)
    {
        /* Number of subsequences is (2**n -1)*/
        int n = str.Length;
        int opsize = (int)Math.Pow(2, n);
 
        /* Generate all subsequences of a given string.
           using counter 000..1 to 111..1*/
        for (int counter = 1; counter < opsize; counter++) {
            var subs = new StringBuilder();
            for (int j = 0; j < n; j++) {
                /* Check if jth bit in the counter is set
                    If set then print jth element from arr[]
                 */
                if ((counter & (1 << j)) != 0)
                    subs.Append(str[j]);
            }
 
            /* Print all permutations of current subsequence
             */
            char[] chars = subs.ToString().ToCharArray();
            Array.Sort(chars);
            do {
                Console.Write(new string(chars) + " ");
            } while (nextPermutation(chars));
        }
    }
    // next permutation function
    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 function
        swap(arr, i, j);
        // Reversing
        reverse(arr, i + 1, arr.Length - 1);
        return true;
    }
    // Swap function
    static void swap(char[] arr, int i, int j)
    {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse function
    static void reverse(char[] arr, int i, int j)
    {
        while (i < j)
            swap(arr, i++, j--);
    }
 
    // Driver program
    public static void Main(string[] args)
    {
        string str = "abc";
        printAll(str);
    }
}


Javascript




/*  Javascript code to generate all possible strings
    that can be formed from given string */
function printAll(str) {
  /* Number of subsequences is (2**n -1)*/
  const n = str.length;
  const opsize = 2 ** n;
   ans = ""
  /* Generate all subsequences of a given string.
     using counter 000..1 to 111..1*/
  for (let counter = 1; counter < opsize; counter++) {
    let subs = "";
    for (let j = 0; j < n; j++) {
      /* Check if jth bit in the counter is set
         If set then append jth element from str */
      if ((counter & (1 << j)) != 0) {
        subs += str.charAt(j);
      }
    }
 
    /* Print all permutations of current subsequence */
    const chars = subs.split("").sort();
    do {
      ans = ans + chars.join("") + " ";
    } while (nextPermutation(chars));
  } console.log(ans);
}
 
// next permutation function
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 function
  swap(arr, i, j);
  // Reversing
  reverse(arr, i + 1, arr.length - 1);
  return true;
}
 
// Swap function
function swap(arr, i, j) {
  const temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}
 
// Reverse function
function reverse(arr, i, j) {
  while (i < j) {
    swap(arr, i++, j--);
  }
}
 
// Driver program
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();
    // Total number of possible combinations
    int combos = (1 << n);
 
    // Generate all possible combinations
    for(int i=1; i<combos; i++)
    {
        string curr_combination = "";
        // Generate current combination using bitmask
        for(int j=0; j<n; j++)
        {
            if(i & (1 << j))
                curr_combination.push_back(str[j]);
        }
 
        // Generate all possible permutations of the current combination
        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();
        // Total number of possible combinations
        int combos = (1 << n);
 
        // Generate all possible combinations
        for (int i = 1; i < combos; i++) {
            StringBuilder curr_combination = new StringBuilder();
            // Generate current combination using bitmask
            for (int j = 0; j < n; j++) {
                if ((i & (1 << j)) != 0)
                    curr_combination.append(str.charAt(j));
            }
 
            // Generate all possible permutations of the current combination
            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));
        }
    }
 
    // Function to generate next permutation
    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;
    }
 
    // Driver code
    public static void main(String[] args) {
        String str = "abc";
        printAll(str);
    }
}


Python3




def print_all(str):
    n = len(str)
 
    # Total number of possible combinations
    combos = (1 << n)
 
    # Generate all possible combinations
    for i in range(1, combos):
        curr_combination = ""
 
        # Generate current combination
        # using bitmask
        for j in range(n):
            if i & (1 << j):
                curr_combination += str[j]
 
        # Generate all possible permutations
        # of the current combination
        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;
        // Total number of possible combinations
        int combos = (1 << n);
 
        // Generate all possible combinations
        for (int i = 1; i < combos; i++)
        {
            List<char> currCombination = new List<char>();
            // Generate current combination using bitmask
            for (int j = 0; j < n; j++)
            {
                if ((i & (1 << j)) != 0)
                    currCombination.Add(str[j]);
            }
 
            // Generate all possible permutations of the current combination
            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); // Backtrack
        }
    }
 
    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;
    // Total number of possible combinations
    const combos = 1 << n;
 
    // Generate all possible combinations
    for (let i = 1; i < combos; i++) {
        let curr_combination = "";
        // Generate current combination using bitmask
        for (let j = 0; j < n; j++) {
            if (i & (1 << j))
                curr_combination += str[j];
        }
 
        // Generate all possible permutations of the current combination
        curr_combination = curr_combination.split('');
        curr_combination.sort();
        do {
            console.log(curr_combination.join(' ') + ' ');
        } while (nextPermutation(curr_combination));
    }
}
 
// Function to generate the next permutation
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 to reverse the array from a given index
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);
 
// This code is contributed by rambabuguphka


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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads