Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word.
Examples:
Input: str = “cd”
Output: cd dc
Input: str = “abb”
Output: abb abb bab bba bab bba
Approach: Write a recursive function that prints every permutation of the given string. Terminating condition will be when the passed string is empty.
Below is the implementation of the above approach:
Java
public class GFG {
static void printPermutn(String str, String ans)
{
if (str.length() == 0 ) {
System.out.print(ans + " " );
return ;
}
for ( int i = 0 ; i < str.length(); i++) {
char ch = str.charAt(i);
String ros = str.substring( 0 , i) +
str.substring(i + 1 );
printPermutn(ros, ans + ch);
}
}
public static void main(String[] args)
{
String s = "abb" ;
printPermutn(s, "" );
}
}
|
Outputabb abb bab bba bab bba
Time Complexity: O(N2), where N is the length of the given string
Auxiliary Space: O(N)
When the permutations need to be distinct.
Examples:
Input: str = “abb”
Output: abb bab bba
Input: str = “geek”
Output: geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg
Approach: Write a recursive function that print distinct permutations. Make a boolean array of size ’26’ which accounts the character being used. If the character has not been used then the recursive call will take place. Otherwise, don’t make any call. Terminating condition will be when the passed string is empty.
Below is the implementation of the above approach:
Java
public class GFG {
static void printDistinctPermutn(String str,
String ans)
{
if (str.length() == 0 ) {
System.out.print(ans + " " );
return ;
}
boolean alpha[] = new boolean [ 26 ];
for ( int i = 0 ; i < str.length(); i++) {
char ch = str.charAt(i);
String ros = str.substring( 0 , i) +
str.substring(i + 1 );
if (alpha[ch - 'a' ] == false )
printDistinctPermutn(ros, ans + ch);
alpha[ch - 'a' ] = true ;
}
}
public static void main(String[] args)
{
String s = "geek" ;
printDistinctPermutn(s, "" );
}
}
|
Outputgeek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg
Time Complexity: O(N2), where N is the length of the given string
Auxiliary Space: O(N)