In this post, we will see how to find all lexicographic permutations of a string where the repetition of characters is allowed.

For example, consider string ABC. It has the following lexicographic permutations with repetition of characters:

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

Practice this problem

The idea is to use recursion to solve this problem. Start by sorting the string so that the characters are processed in the lexicographical order. Then at any point in the recursion, the current index in the output string is filled with each character of the input string one by one, and recur for the next index.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
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

The above solution doesn’t handle duplicates in the output. For example, for string AAB, it prints the following:

AAA AAA AAB AAA AAA AAB ABA ABA ABB AAA AAA AAB AAA AAA AAB ABA ABA ABB BAA BAA BAB BAA BAA BAB BBA BBA BBB

Here, AAA is repeated 8 times. AAB, ABA, and BAA are repeated 4 times. Similarly, ABB, BAB, BBA are repeated 2 times. The following code efficiently handles duplicates in the output:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
AAA AAB ABA ABB BAA BAB BBA BBB

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).