VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-permutations-with-repetition-of-characters/

⇱ Print all permutations with repetition of characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all permutations with repetition of characters

Last Updated : 13 Sep, 2022

Given a string of length n, print all permutations of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order 

Examples: 

Input: AB
Output:
All permutations of AB with repetition are:
AA
AB
BA
BB

Input: ABC
Output: 
All permutations of ABC with repetition are:
AAA
AAB
AAC
ABA
...
...
CCB
CCC

For an input string of size n, there will be n^n permutations with repetition allowed. The idea is to fix the first character at first index and recursively call for other subsequent indexes. Once all permutations starting with the first character are printed, fix the second character at first index. Continue these steps till last character. Thanks to PsychoCoder for providing the following C implementation.  


Output
All permutations with repetition of ABC are: 
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC

Time Complexity: O(n^n)
Auxiliary Space: O(n)


Following is recursion tree for input string "AB". The purpose of recursion tree is to help in understanding the above implementation as it shows values of different variables. 

 data="" 
 / \
 / \ 
 index=0 index=0
 i=0 i=1 
 data="A" data="B"
 / \ / \
 / \ / \
 index=1 index=1 index=1 index=1 
 i=0 i=1 i=0 i=1 
 data="AA" data="AB" data="BA" data="BB"

In the above implementation, it is assumed that all characters of the input string are different. The implementation can be easily modified to handle the repeated characters. We have to add a preprocessing step to find unique characters (before calling allLexicographicRecur()). 

Comment
Article Tags: