GeeksforGeeks App
Open App
Browser
Continue

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.

Examples:

Input : BAC
Output : ABC ACB BAC BCA CAB CBA

Input : AAB
Output : AAB ABA BAA

Input : DBCA

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 until 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”.

Here is the implementation of this problem –

C++

 `// C++ program to print all permutations``// of a string in sorted order.``#include ``using` `namespace` `std;` `// Calculating factorial of a number``int` `factorial(``int` `n)``{``    ``int` `f = 1;``    ``for` `(``int` `i = 1; i <= n; i++)``        ``f = f * i;``    ``return` `f;``}` `// Method to find total number of permutations``int` `calculateTotal(string temp, ``int` `n)``{``    ``int` `f = factorial(n);` `    ``// Building Map to store frequencies of``    ``// all characters.``    ``map<``char``, ``int``> hm;``    ``for` `(``int` `i = 0; i < temp.length(); i++)``    ``{``        ``hm[temp[i]]++;``    ``}` `    ``// Traversing map and``    ``// finding duplicate elements.``    ``for` `(``auto` `e : hm)``    ``{``        ``int` `x = e.second;``        ``if` `(x > 1)``        ``{``            ``int` `temp5 = factorial(x);``            ``f /= temp5;``        ``}``        ``return` `f;``    ``}``}` `static` `void` `nextPermutation(string &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]) and``            ``(temp[j] > x))``            ``min = j;` `    ``// Swapping the above found characters.``    ``swap(temp[i - 1], temp[min]);` `    ``// Sort all digits from position next to 'i-1'``    ``// to end of the string.``    ``sort(temp.begin() + i, temp.end());` `    ``// Print the String``    ``cout << temp << endl;``}` `void` `printAllPermutations(string s)``{``    ` `    ``// Sorting String``    ``string temp(s);``    ``sort(temp.begin(), temp.end());` `    ``// Print first permutation``    ``cout << temp << endl;` `    ``// Finding the total permutations``    ``int` `total = calculateTotal(temp, temp.length());``    ``for` `(``int` `i = 1; i < total; i++)``    ``{``        ``nextPermutation(temp);``    ``}``}` `// Driver Code``int` `main()``{``    ``string s = ``"AAB"``;``    ``printAllPermutations(s);``}` `// This code is contributed by``// sanjeev2552`

Java

 `// 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 hm =``                     ``new` `HashMap();``    ``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);``  ``}``}`

Python3

 `# Python3 program to print``# all permutations of a``# string in sorted order.``from` `collections ``import` `defaultdict` `# Calculating factorial``# of a number``def` `factorial(n):` `    ``f ``=` `1``    ` `    ``for` `i ``in` `range` `(``1``, n ``+` `1``):``        ``f ``=` `f ``*` `i``    ``return` `f` `# Method to find total``# number of permutations``def` `calculateTotal(temp, n):` `    ``f ``=` `factorial(n)` `    ``# Building Map to store``    ``# frequencies of all``    ``# characters.``    ``hm ``=` `defaultdict (``int``)``    ` `    ``for` `i ``in` `range` `(``len``(temp)):``        ``hm[temp[i]] ``+``=` `1``   ` `    ``# Traversing map and``    ``# finding duplicate elements.``    ``for` `e ``in` `hm:``        ``x ``=` `hm[e]``        ``if` `(x > ``1``):``            ``temp5 ``=` `factorial(x)``            ``f ``/``/``=` `temp5``        ``return` `f` `def` `nextPermutation(temp):``    ` `    ``# Start traversing from``    ``# the end and find position``    ``# 'i-1' of the first character``    ``# which is greater than its successor``    ``for` `i ``in` `range` `(``len``(temp) ``-` `1``, ``0``, ``-``1``):``        ``if` `(temp[i] > temp[i ``-` `1``]):``            ``break` `    ``# Finding smallest character``    ``# after 'i-1' and greater``    ``# than temp[i-1]``    ``min` `=` `i``    ``x ``=` `temp[i ``-` `1``]``    ``for` `j ``in` `range` `(i ``+` `1``, ``len``(temp)):``        ``if` `((temp[j] < temp[``min``]) ``and``            ``(temp[j] > x)):``            ``min` `=` `j` `    ``# Swapping the above``    ``# found characters.``    ``temp[i ``-` `1``], temp[``min``] ``=` `(temp[``min``],``                              ``temp[i ``-` `1``])` `    ``# Sort all digits from``    ``# position next to 'i-1'``    ``# to end of the string``    ``temp[i:].sort()` `    ``# Print the String``    ``print` `(''.join(temp))` `def` `printAllPermutations(s):``    ` `    ``# Sorting String``    ``temp ``=` `list``(s)``    ``temp.sort()` `    ``# Print first permutation``    ``print` `(''.join( temp))` `    ``# Finding the total permutations``    ``total ``=` `calculateTotal(temp,``                           ``len``(temp))``    ``for` `i ``in` `range` `(``1``, total):``        ``nextPermutation(temp)` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``s ``=` `"AAB"``    ``printAllPermutations(s)` `# This code is contributed by Chitranayal`

C#

 `// C# program to print all permutations``// of a string in sorted order.``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{` `// 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++)``    ``Console.Write(temp[i]);``    ``Console.WriteLine();``}` `// Method to find total number of permutations``static` `int` `calculateTotal(``char``[] temp, ``int` `n)``{``    ``int` `f = factorial(n);` `    ``// Building Dictionary to store frequencies ``    ``// of all characters.``    ``Dictionary<``char``,``               ``int``> hm = ``new` `Dictionary<``char``,``                                        ``int``>();``    ``for` `(``int` `i = 0; i < temp.Length; i++)``    ``{``        ``if` `(hm.ContainsKey(temp[i]))``            ``hm[temp[i]] = hm[temp[i]] + 1;``        ``else``            ``hm.Add(temp[i], 1);``    ``}` `    ``// Traversing hashmap and``    ``// finding duplicate elements.``    ``foreach``(KeyValuePair<``char``, ``int``> e ``in` `hm)``    ``{``        ``int` `x = e.Value;``        ``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.``    ``Array.Sort(temp, i, temp.Length-i);` `    ``// Print the String``    ``print(temp);``}` `static` `void` `printAllPermutations(String s)``{` `    ``// Sorting String``    ``char` `[]temp = s.ToCharArray();``    ``Array.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);``}``}` `// This code is contributed by Rajput-Ji`

Javascript

 ``

Output

```AAB
ABA
BAA
```

Time Complexity: O(n*m) where n is the size of the array and m is the number of permutations possible.
Auxiliary Space: O(n).

My Personal Notes arrow_drop_up