Print all distinct permutation of a string having duplicates.
Input : ABCA Output : AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAA
An algorithm to print all distinct permutations has already been discussed here. Here we’ll discuss one more approach to do the same. Recall first how we print permutations without any duplicates in the input string. It is given here. Let’s now take the case of the string “ABAC”. While generating permutations, let’s say we are at index = 0, swap it with all elements after it. When we reach at i=2, we see that in the string s[index…i-1], there was an index which is equal to s[i]. Thus, swapping it will produce repeated permutations. Thus, we don’t swap it. The below explains it better.
Illustration : Let us understand with below example.
i = 0 1 2 3 A B A C index = 0, s = A Start swapping s[index] with s[i] following it: i = index + 1 = 1 Since s[index] != s[i], swap and recur. i = 2, s[index] == s[i], don't swap i = 3, s[index] != s[i], swap and recur.
Below code does the same.
ABCA ABAC ACBA ACAB AACB AABC BACA BAAC BCAA CBAA CABA CAAB
This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print all distinct permutations of a given string with duplicates
- Distinct permutations of a string containing duplicates using HashSet in Java
- Print first n distinct permutations of string using itertools in Python
- Java Program to print distinct permutations of a string
- Iterative program to generate distinct Permutations of a String
- Print distinct sorted permutations with duplicates allowed in input
- Find distinct characters in distinct substrings of a string
- Permutations of a given string using STL
- All permutations of a string using iteration
- Print all palindrome permutations of a string
- Permutations of string such that no two vowels are adjacent
- Print all permutations of a string in Java
- Time complexity of all permutations of a string
- Generate all permutations of a string that follow given constraints
- Write a program to print all permutations of a given string