Print all distinct permutations of a given string with duplicates
Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output.
Input: str = "AB" Output: AB BA Input: str = "AA" Output: AA Input: str = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str = "ABA" Output: ABA AAB BAA Input: str = "ABCA" Output: AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAA
We have discussed an algorithm to print all permutations in below post. It is strongly recommended to refer below post as a prerequisite of this post.
Write a C program to print all permutations of a given string
The algorithm discussed on above link doesn’t handle duplicates.
1 ABCC 2 ACBC 3 ACCB 4 BACC 5 BCAC 6 BCCA 7 CABC 8 CACB 9 CBAC 10 CBCA 11 CCAB 12 CCBA
The above code is taken from a comment below by Mr. Lazy.
Time Complexity: O(n2 * n!)
Auxiliary Space: O(1)
The above algorithm is in the time complexity of O(n2 * n!) but we can achieve a better time complexity of O(n!*n) which was there in the case of all distinct characters in the input by some modification in that algorithm. The distinct characters algorithm can be found here – https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Efficient Approach: In our recursive function to find all permutations, we can use unordered_set for taking care of duplicate element remaining in the active string. While iterating over the elements of the string, we will check for that element in the unordered_set and if it found then we will skip that iteration or otherwise we will insert that element into unordered_set. As on an average all the unordered_set operations like insert() and find() are in O(1) time then the algorithm time complexity will not change by using unordered_set.
The algorithm implementation is as follows –
ABCC ACBC ACCB BACC BCAC BCCA CABC CACB CBAC CBCA CCAB CCBA
Time Complexity – O(n*n!)
Auxiliary Space – O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above