Print distinct sorted permutations with duplicates allowed in input
Write a program to print all distinct permutations of a given string in sorted order. Note that the input string may contain duplicate characters.
In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting.
Source – Wikipedia
Input : BAC
Output : ABC ACB BAC BCA CAB CBA
Input : AAB
Output : AAB ABA BAA
Input : DBCA
Output: ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB DBAC DBCA DCAB DCBA
Concept Used: The number of Strings generated by a string of distinct characters of length ‘n’ is equal to ‘n!’. Sorting any given string and generating the lexicographically next bigger string until we reach the largest lexicographically string from those characters.
Different permutations of word “geeks”
Length of string = 5
Character ‘e’ repeats 2 times.
Result = 5!/2! = 60.
Example: Consider a string “ABCD”.
Step 1: Sort the string.
Step 2: Obtain the total number of permutations which can be formed from that string.
Step 3: Print the sorted string and then loop for the number of (permutations-1) times as 1st string is already printed.
Step 4: Find the next greater string,.
Here is the implementation of this problem –
AAB ABA BAA
Time Complexity: O(n*m) where n is the size of the array and m is the number of permutations possible.
Auxiliary Space: O(n).