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 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
- Distinct permutations of a string containing duplicates using HashSet in Java
- Print k different sorted permutations of a given array
- Java Program to print distinct permutations of a string
- Print first n distinct permutations of string using itertools in Python
- Print all permutations in sorted (lexicographic) order
- Print all the duplicates in the input string
- Longest common subsequence with permutations allowed
- Generate permutations with only adjacent swaps 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
- Iterative program to generate distinct Permutations of a String
- 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