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++
/* 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);
Outputa 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
Outputa 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)
Similar Reads
Print all possible strings of length k that can be formed from a set of n characters Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set. Examples: Input: set[] = {'a', 'b'}, k = 3 Output: aaa aab aba abb baa bab bba bbb Input: set[] = {'a', 'b', 'c', 'd'}, k = 1 Output: a b c d For a given set of size n, t
6 min read
Print all Substrings of length n possible from the given String Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = âgeeksforgeeksâ, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are âgeeâ, âeekâ, âeksâ, âksfâ, âsfoâ, âforâ, âorgâ, ârge
8 min read
Print all possible strings that can be made by placing spaces Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. Recommended PracticePermutation with SpacesTry It! The idea is to use
11 min read
Number of ways to form a given String from the given set of Strings Given a string str and an array of strings dictionary[], the task is to find the number of ways str can be formed as a concatenation of strings (any number of times) in a dictionary[]. Examples: Input: str = abab, dictionary[] = { a, b, ab }Output: 4Explanation: There are 4 ways to form string str a
15+ min read
Length of longest common prefix possible by rearranging strings in a given array Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {âaabdcâ, âabcdâ, âaacdâ}Output: 3Explanation: Rearrange characters of each string of the given array such that the a
8 min read
Length of all prefixes that are also the suffixes of given string Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S. Examples: Input: S = "ababababab"Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are: "ab" of length = 2"abab" of le
10 min read