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

Examples:

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print all permutations of a string
// in sorted order.
import java.io.*;
import java.util.*;
  
class Solution {
  
  // Calculating factorial of a number
  static int factorial(int n) {
    int f = 1;
    for (int i = 1; i <= n; i++)
      f = f * i;
    return f;
  }
  
  // Method to print the array
  static void print(char[] temp) {
    for (int i = 0; i < temp.length; i++)
      System.out.print(temp[i]);
    System.out.println();
  }
  
  // Method to find total number of permutations
  static int calculateTotal(char[] temp, int n) {
    int f = factorial(n);
  
    // Building HashMap to store frequencies of 
    // all characters.
    HashMap<Character, Integer> hm = 
                     new HashMap<Character, Integer>();
    for (int i = 0; i < temp.length; i++) {
      if (hm.containsKey(temp[i]))
        hm.put(temp[i], hm.get(temp[i]) + 1);
      else
        hm.put(temp[i], 1);
    }
  
    // Traversing hashmap and finding duplicate elements.
    for (Map.Entry e : hm.entrySet()) {
      Integer x = (Integer)e.getValue();
      if (x > 1) {
        int temp5 = factorial(x);
        f = f / temp5;
      }
    }
    return f;
  }
  
  static void nextPermutation(char[] temp) {
  
    // Start traversing from the end and
    // find position 'i-1' of the first character 
    // which is greater than its  successor. 
    int i;
    for (i = temp.length - 1; i > 0; i--)
      if (temp[i] > temp[i - 1])
        break;
  
    // Finding smallest character after 'i-1' and
    // greater than temp[i-1]
    int min = i;
    int j, x = temp[i - 1];
    for (j = i + 1; j < temp.length; j++)
      if ((temp[j] < temp[min]) && (temp[j] > x))
        min = j;
  
    // Swapping the above found characters.
    char temp_to_swap;
    temp_to_swap = temp[i - 1];
    temp[i - 1] = temp[min];
    temp[min] = temp_to_swap;
  
    // Sort all digits from position next to 'i-1'
    // to end of the string.
    Arrays.sort(temp, i, temp.length);
  
    // Print the String
    print(temp);
  }
  
  static void printAllPermutations(String s) {
  
    // Sorting String
    char temp[] = s.toCharArray();
    Arrays.sort(temp);
  
    // Print first permutation
    print(temp);
  
    // Finding the total permutations
    int total = calculateTotal(temp, temp.length);
    for (int i = 1; i < total; i++)
      nextPermutation(temp);
  }
  
  // Driver Code
  public static void main(String[] args) {
    String s = "AAB";
    printAllPermutations(s);
  }
}

chevron_right


Output:

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).



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.