Distinct permutations of the string | Set 2
Last Updated :
05 Feb, 2025
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 use backtracking to generate all possible permutations of given string s. To do so, first initialise an array of string ans[] to list all the permutations and a HashSet res to store all the unique strings in lexicographically sorted order.Start from the 0th index and for each index i, swap the value s[i] with all the elements in its right i.e. from i+1 to n-1, and recur to the index i + 1. If the index i is equal to n, store the resultant string in res, else keep operating similarly for all other indices. Thereafter, swap back the values to original values to initiate backtracking. At last insert the elements in array ans[].
Recursion Tree for permutations of string "ABC"Below is the implementation of the above approach:
C++
// C++ Program to generate all unique
// permutations of a string
#include <bits/stdc++.h>
using namespace std;
// Recursive function to generate
// all permutations of string s
void recurPermute(int index, string &s,
set<string> &ans) {
// Base Case
if (index == s.size()) {
ans.insert(s);
return;
}
// Swap the current index with all
// possible indices and recur
for (int i = index; i < s.size(); i++) {
swap(s[index], s[i]);
recurPermute(index + 1, s, ans);
swap(s[index], s[i]);
}
}
// Function to find all unique permutations
vector<string> findPermutation(string &s) {
// sort input string
sort(s.begin(), s.end());
// Stores the final answer
vector<string> ans;
// Stores all unique permutations
set<string> res;
recurPermute(0, s, res);
// Copy all unique permutations
// to the final answer
for (auto x : res) {
ans.push_back(x);
}
return ans;
}
int main() {
string s = "ABC";
vector<string> res = findPermutation(s);
for(auto x: res) {
cout << x << " ";
}
return 0;
}
Java
// Java Program to generate all unique
// permutations of a string
import java.util.*;
class GfG {
// Recursive function to generate
// all permutations of string s
static void recurPermute(int index, StringBuilder s,
Set<String> ans) {
// Base Case
if (index == s.length()) {
ans.add(s.toString());
return;
}
// Swap the current index with all
// possible indices and recur
for (int i = index; i < s.length(); i++) {
char temp = s.charAt(index);
s.setCharAt(index, s.charAt(i));
s.setCharAt(i, temp);
recurPermute(index + 1, s, ans);
temp = s.charAt(index);
s.setCharAt(index, s.charAt(i));
s.setCharAt(i, temp);
}
}
// Function to find all unique permutations
static List<String> findPermutation(String s) {
// sort input string
char[] sorted = s.toCharArray();
Arrays.sort(sorted);
s = new String(sorted);
// Stores the final answer
List<String> ans = new ArrayList<>();
// Stores all unique permutations
Set<String> res = new TreeSet<>();
recurPermute(0, new StringBuilder(s), res);
// Copy all unique permutations
// to the final answer
ans.addAll(res);
return ans;
}
public static void main(String[] args) {
String s = "ABC";
List<String> res = findPermutation(s);
for (String x : res) {
System.out.print(x + " ");
}
}
}
Python
# Python Program to generate all unique
# permutations of a string
# Recursive function to generate
# all permutations of string s
def recurPermute(index, s, ans):
# Base Case
if index == len(s):
ans.add("".join(s))
return
# Swap the current index with all
# possible indices and recur
for i in range(index, len(s)):
s[index], s[i] = s[i], s[index]
recurPermute(index + 1, s, ans)
s[index], s[i] = s[i], s[index]
# Function to find all unique permutations
def findPermutation(s):
# sort input string
s = "".join(sorted(s))
# Stores all unique permutations
res = set()
recurPermute(0, list(s), res)
# Convert set to list for the final answer
return sorted(list(res))
if __name__ == "__main__":
s = "ABC"
res = findPermutation(s)
print(" ".join(res))
C#
// C# Program to generate all unique
// permutations of a string
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to generate
// all permutations of string s
static void recurPermute(int index, char[] s,
SortedSet<string> ans) {
// Base Case
if (index == s.Length) {
ans.Add(new string(s));
return;
}
// Swap the current index with all
// possible indices and recur
for (int i = index; i < s.Length; i++) {
char temp = s[index];
s[index] = s[i];
s[i] = temp;
recurPermute(index + 1, s, ans);
temp = s[index];
s[index] = s[i];
s[i] = temp;
}
}
// Function to find all unique permutations
static List<string> findPermutation(string s) {
// sort input string
char[] sorted = s.ToCharArray();
Array.Sort(sorted);
s = new string(sorted);
// Stores the final answer
List<string> ans = new List<string>();
// Stores all unique permutations
SortedSet<string> res = new SortedSet<string>();
recurPermute(0, s.ToCharArray(), res);
// Copy all unique permutations
// to the final answer
ans.AddRange(res);
return ans;
}
static void Main(string[] args) {
string s = "ABC";
List<string> res = findPermutation(s);
foreach (string x in res) {
Console.Write(x + " ");
}
}
}
JavaScript
// JavaScript Program to generate all unique
// permutations of a string
// Recursive function to generate
// all permutations of string s
function recurPermute(index, s, ans) {
// Base Case
if (index === s.length) {
ans.add(s.join(""));
return;
}
// Swap the current index with all
// possible indices and recur
for (let i = index; i < s.length; i++) {
[s[index], s[i]] = [s[i], s[index]];
recurPermute(index + 1, s, ans);
[s[index], s[i]] = [s[i], s[index]];
}
}
// Function to find all unique permutations
function findPermutation(s) {
// sort input string
s = s.split("").sort();
// Stores all unique permutations
let res = new Set();
recurPermute(0, s, res);
// Convert Set to Array for the final answer
return Array.from(res).sort();
}
//Driver code
const s = "ABC";
const res = findPermutation(s);
console.log(res.join(" "));
OutputABC ACB BAC BCA CAB CBA
Time Complexity: O(n * n!)
Auxiliary Space: O(n!)
Note: The given problem can also solved using Recursion and STL. These approaches are discussed in below given articles:
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem