 Open in App
Not now

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

• Difficulty Level : Medium
• Last Updated : 24 Mar, 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
dca bcd bdc cbd cdb dbc dcb abcd abdc
dabc dacb dbac dbca dcab dcba ```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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

## 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``<

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)