Open In App

Print distinct sorted permutations with duplicates allowed in input

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order.

Note: A permutation is the rearrangement of all the elements of a string.

Examples:

Input: s = “ABC”
Output: “ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”

Input: s = “XY”
Output: “XY”, “YX”

Input: s = “AAA”
Output: “AAA”

Approach:

The idea is to keep generating the next permutation of given string s until it becomes equal to original string. To do so, firstly create an array ans[] to store the modified strings. Sort the array that ensures that the strings will be generated in lexicographically sorted order. Store the sorted string in auxiliary string x and keep generating next permutation until the modified string s is not equal to string x.

To generate next permutation of string s:

  • Iterate over the given string s from end and find the first index (pivot) which doesn’t follow property of non-increasing suffix, (i.e,  s[i] < s[i + 1]).
  • If pivot index does not exist, then the given sequence in the string is the largest as possible. So, reverse the complete string. For example, for “ABC” the output would be “CBA”
  • Otherwise, Iterate the array from the end and find for the successor (rightmost greater character) of pivot in suffix.
  • Swap the pivot and successor
  • Minimize the suffix part by reversing the string from pivot + 1 till n.

Note: The article Next Permutation covers the process and idea of generating next permutation for integer array in detail. Same process can be followed to generate next permutation for string.

C++
// C++ program to print all permutations 
// of a string in sorted order.
#include <bits/stdc++.h>
using namespace std;

// Function to generate next permutation
void nextPermutation(string &s) {
  
    int n = s.size(); 

    // Find the pivot index
    int pivot = -1; 
    for (int i = n - 2; i >= 0; i--) {
        if (s[i] < s[i + 1]) {
            pivot = i;
            break;
        }
    }

    // If pivot point does not exist, reverse the
    // whole string
    if (pivot == -1) {
        reverse(s.begin(), s.end());
        return;
    }

    // find the element from the right that
    // is greater than pivot
    for (int i = n - 1; i > pivot; i--) {
        if (s[i] > s[pivot]) {
            swap(s[i], s[pivot]);
            break;
        }
    }

    // Reverse the elements from pivot + 1 to the 
    // end to get the next permutation
    reverse(s.begin() + pivot + 1, s.end());
}

// Function to find all permutations of a given string
vector<string> findPermutation(string &s) {

    // stores all unique permutations
    vector<string> ans;

    // sort the string to generate
    // all permutations in sorted order
    sort(s.begin(), s.end());

    // store given string s in string x
    // to check if all permutations are generated
    string x = s;

    // iterate till x is not equal to s
    do {
        ans.push_back(s);
        nextPermutation(s);
    } while(s != x);

    return ans;
}

int main() {
    string s = "ABC";
    vector<string> ans = findPermutation(s);
    for(auto i: ans){
        cout << i << " ";
    }
    return 0;
}
Java
// Java program to print all permutations 
// of a string in sorted order.
import java.util.*;

class GfG {

    // Function to generate next permutation
    static void nextPermutation(StringBuilder s) {
        int n = s.length();

        // Find the pivot index
        int pivot = -1;
        for (int i = n - 2; i >= 0; i--) {
            if (s.charAt(i) < s.charAt(i + 1)) {
                pivot = i;
                break;
            }
        }

        // If pivot point does not exist
      	// reverse the whole string
        if (pivot == -1) {
            s.reverse();
            return;
        }

        // Find the element from the right 
      	// that is greater than pivot
        for (int i = n - 1; i > pivot; i--) {
            if (s.charAt(i) > s.charAt(pivot)) {
                char temp = s.charAt(i);
                s.setCharAt(i, s.charAt(pivot));
                s.setCharAt(pivot, temp);
                break;
            }
        }

        // Reverse the elements from pivot + 1 to 
      	// the end to get the next permutation
        int start = pivot + 1, end = n - 1;
      
        while (start < end) {
            char temp = s.charAt(start);
            s.setCharAt(start, s.charAt(end));
            s.setCharAt(end, temp);
            start++;
            end--;
        }
    }

    // Function to find all permutations of a given string
    static List<String> findPermutation(String s) {
        List<String> ans = new ArrayList<>();

        // Sort the string to generate 
      	// all permutations in sorted order
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        StringBuilder str = 
          	new StringBuilder(new String(chars));

        // Store the sorted string for comparison
        String x = str.toString();

        // Iterate till x is not equal to the string
        do {
            ans.add(str.toString());
            nextPermutation(str);
        } while (!str.toString().equals(x));

        return ans;
    }

    public static void main(String[] args) {
        String s = "ABC";
        List<String> ans = findPermutation(s);
        for (String i : ans) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print all permutations 
# of a string in sorted order.

# Function to generate next permutation
def nextPermutation(s):
    s = list(s)
    n = len(s)

    # Find the pivot index
    pivot = -1
    for i in range(n - 2, -1, -1):
        if s[i] < s[i + 1]:
            pivot = i
            break

    # If pivot point does not exist
    # reverse the whole string
    if pivot == -1:
        s.reverse()
        return ''.join(s)

    # Find the element from the right that is greater than pivot
    for i in range(n - 1, pivot, -1):
        if s[i] > s[pivot]:
            s[i], s[pivot] = s[pivot], s[i]
            break

    # Reverse the elements from pivot + 1 to the end
    s = s[:pivot + 1] + s[pivot + 1:][::-1]
    return ''.join(s)

# Function to find all permutations of a given string
def findPermutation(s):
    ans = []

    # Sort the string to generate 
    # all permutations in sorted order
    s = ''.join(sorted(s))

    # Store the sorted string for comparison
    x = s

    # Iterate till x is not equal to the string
    while True:
        ans.append(s)
        s = nextPermutation(s)
        if s == x:
            break

    return ans

if __name__ == "__main__":
    s = "ABC"
    ans = findPermutation(s)
    print(" ".join(ans))
C#
// C# program to print all permutations 
// of a string in sorted order.
using System;
using System.Collections.Generic;

class GfG {

    // Function to generate next permutation
    static void NextPermutation(char[] s) {
        int n = s.Length;

        // Find the pivot index
        int pivot = -1;
        for (int i = n - 2; i >= 0; i--) {
            if (s[i] < s[i + 1]) {
                pivot = i;
                break;
            }
        }

        // If pivot point does not exist
      	// reverse the whole string
        if (pivot == -1) {
            Array.Reverse(s);
            return;
        }

        // Find the element from the right 
      	// that is greater than pivot
        for (int i = n - 1; i > pivot; i--) {
            if (s[i] > s[pivot]) {
                char temp = s[i];
                s[i] = s[pivot];
                s[pivot] = temp;
                break;
            }
        }

        // Reverse the elements from pivot + 1 to the end
        Array.Reverse(s, pivot + 1, n - pivot - 1);
    }

    // Function to find all permutations of a given string
    static List<string> FindPermutation(string s) {
        List<string> ans = new List<string>();

        // Sort the string to generate 
      	// all permutations in sorted order
        char[] chars = s.ToCharArray();
        Array.Sort(chars);
        string str = new string(chars);

        // Store the sorted string for comparison
        string x = str;

        // Iterate till x is not equal to the string
        do {
            ans.Add(str);
            char[] temp = str.ToCharArray();
            NextPermutation(temp);
            str = new string(temp);
        } while (str != x);

        return ans;
    }

    static void Main() {
        string s = "ABC";
        List<string> ans = FindPermutation(s);
        foreach (string i in ans) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// JavaScript program to print all permutations 
// of a string in sorted order.

// Function to generate next permutation
function nextPermutation(s) {
    let arr = s.split('');
    let n = arr.length;

    // Find the pivot index
    let pivot = -1;
    for (let i = n - 2; i >= 0; i--) {
        if (arr[i] < arr[i + 1]) {
            pivot = i;
            break;
        }
    }

    // If pivot point does not exist
    // reverse the whole string
    if (pivot === -1) {
        arr.reverse();
        return arr.join('');
    }

    // Find the element from the right 
    // that is greater than pivot
    for (let i = n - 1; i > pivot; i--) {
        if (arr[i] > arr[pivot]) {
            [arr[i], arr[pivot]] = [arr[pivot], arr[i]];
            break;
        }
    }

    // Reverse the elements from pivot + 1 to the end
    let left = pivot + 1, right = n - 1;
    while (left < right) {
        [arr[left], arr[right]] = [arr[right], arr[left]];
        left++;
        right--;
    }

    return arr.join('');
}

// Function to find all permutations of a given string
function findPermutation(s) {
    let ans = [];

    // Sort the string to generate all permutations in sorted order
    s = s.split('').sort().join('');

    // Store the sorted string for comparison
    const x = s;

    // Iterate till x is not equal to the string
    do {
        ans.push(s);
        s = nextPermutation(s);
    } while (s !== x);

    return ans;
}

const s = "ABC";
const ans = findPermutation(s);
console.log(ans.join(' '));

Output
ABC ACB BAC BCA CAB CBA 

Time Complexity: O(n * n!), where n is the size of the string.
Auxiliary Space: O(n)

Related Articles:



Next Article

Similar Reads