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 till 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.
Steps : 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 number of (permutations-1) times as 1st string is already printed.
Step 4 : Find next greater string,.
Here is the Java Implementation of this problem –
AAB ABA BAA
Time Complexity: O(n*m) where n is size of array and m is number of permutations possible .
Auxiliary Space: O(n).
- Print all distinct permutations of a given string with duplicates
- Print first n distinct permutations of string using itertools in Python
- Java Program to print distinct permutations of a string
- Print k different sorted permutations of a given array
- Print all the duplicates in the input string
- Print all permutations in sorted (lexicographic) order
- Generate permutations with only adjacent swaps allowed
- Longest common subsequence with permutations allowed
- Minimum insertions to form a palindrome with permutations allowed
- Distinct permutations of the string | Set 2
- Distinct strings with odd and even changes allowed
- Count number of triplets with product equal to given number with duplicates allowed
- Count number of triplets with product equal to given number with duplicates allowed | Set-2
- Print all palindrome permutations of a string
- Print all permutations of a string in Java
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.