Print all Unique permutations of a given string.
Last Updated :
23 Jul, 2025
Given a string that may contain duplicates, the task is find all unique permutations of given string in any order.
Examples:
Input: "ABC"
Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]
Explanation: Given string ABC has 6 unique permutations as "ABC", "ACB", "BAC", "BCA", "CAB" and "CBA".
Input: "AAA"
Output: ["AAA"]
Explanation: No other unique permutations can be formed as all the characters are same.
[Naive Approach] Generating All Permutations
The idea is to generate all possible permutations of a given string and store them in a hash set. The generated permutations were stored in hash set, to ensures that only unique permutations are retained as hashset does not allow duplicates. Once all permutations have been generated, we transfer the permutations from hash set to the result array.
This method is particularly useful when dealing with input strings that contain duplicate characters. Instead of manually handling the duplicates during the permutation generation, the use of a unordered set simplifies the process by eliminating duplicates automatically.
CPP
// C++ program to print unique permutation of string using hash set.
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
// Function genPermutation is used to generate all possible permutaion.
void genPermutation(int i, string &s, vector<bool> &used,
string &curr, unordered_set<string>& st) {
if (i == s.size()) {
// Add the permutation to the result set
st.insert(curr);
return;
}
for (int j = 0; j < s.size(); j++) {
if (!used[j]) {
// Mark the character as used
used[j] = true;
curr.push_back(s[j]);
// Recurse with the next character
genPermutation(i + 1, s, used, curr,st);
// Backtrack and unmark the character
used[j] = false;
curr.pop_back();
}
}
}
vector<string> findPermutation(string &s) {
// To track if a character is used
vector<bool> used(s.size(), false);
unordered_set<string> st;
string curr = "";
// Start the recursion
genPermutation(0, s, used, curr, st);
// Convert the set to a vector
vector<string> res(st.begin(), st.end());
return res;
}
int main() {
string s = "ABC";
vector<string> res = findPermutation(s);
// Print the permutations
for (string perm: res)
cout << perm << " ";
return 0;
}
Java
// Java program to print unique permutation of string using hash set.
import java.util.ArrayList;
import java.util.HashSet;
class GfG {
// Function genPermutation is used to generate all possible permutation.
static void genPermutation(int i, String s, boolean[] used,
StringBuilder curr, HashSet<String> st) {
if (i == s.length()) {
// Add the permutation to the result set
st.add(curr.toString());
return;
}
for (int j = 0; j < s.length(); j++) {
if (!used[j]) {
// Mark the character as used
used[j] = true;
curr.append(s.charAt(j));
// Recur with the next character
genPermutation(i + 1, s, used, curr, st);
// Backtrack and unmark the character
used[j] = false;
curr.deleteCharAt(curr.length() - 1);
}
}
}
static ArrayList<String> findPermutation(String s) {
// To track if a character is used
boolean[] used = new boolean[s.length()];
HashSet<String> st = new HashSet<>();
StringBuilder curr = new StringBuilder();
// Start the recursion
genPermutation(0, s, used, curr, st);
// Convert the set to a list
return new ArrayList<>(st);
}
public static void main(String[] args) {
String s = "ABC";
ArrayList<String> res = findPermutation(s);
// Print the permutations
for (String perm : res) {
System.out.print(perm + " ");
}
}
}
Python
# Python program to print unique permutation of string using hash set.
# Function genPermutation is used to generate all possible permutation.
def genPermutation(i, s, used, curr, st):
if i == len(s):
# Add the permutation to the result set
st.add("".join(curr))
return
for j in range(len(s)):
if not used[j]:
# Mark the character as used
used[j] = True
curr.append(s[j])
# Recurse with the next character
genPermutation(i + 1, s, used, curr, st)
# Backtrack and unmark the character
used[j] = False
curr.pop()
def findPermutation(s):
# To track if a character is used
used = [False] * len(s)
st = set()
curr = []
# Start the recursion
genPermutation(0, s, used, curr, st)
# Convert the set to a list
return list(st)
if __name__ == "__main__":
s = "ABC"
res = findPermutation(s)
# Print the permutations
for perm in res:
print(perm, end=" ")
C#
// C# program to print unique permutation of string using hash set.
using System;
using System.Collections.Generic;
class GfG {
// Function genPermutation is used to generate all possible permutation.
static void genPermutation(int i, string s, bool[] used,
List<char> curr, HashSet<string> st) {
if (i == s.Length) {
// Add the permutation to the result set
st.Add(new string(curr.ToArray()));
return;
}
for (int j = 0; j < s.Length; j++) {
if (!used[j]) {
// Mark the character as used
used[j] = true;
curr.Add(s[j]);
// Recurse with the next character
genPermutation(i + 1, s, used, curr, st);
// Backtrack and unmark the character
used[j] = false;
curr.RemoveAt(curr.Count - 1);
}
}
}
static List<string> findPermutation(string s) {
// To track if a character is used
bool[] used = new bool[s.Length];
HashSet<string> st = new HashSet<string>();
List<char> curr = new List<char>();
// Start the recursion
genPermutation(0, s, used, curr, st);
// Convert the set to a list
return new List<string>(st);
}
static void Main(string[] args) {
string s = "ABC";
List<string> res = findPermutation(s);
// Print the permutations
foreach (string perm in res) {
Console.Write(perm + " ");
}
}
}
JavaScript
// JavaScript program to print unique permutation of string using hash set.
// Function genPermutation is used to generate all possible permutation.
function genPermutation(i, s, used, curr, st) {
if (i === s.length) {
// Add the permutation to the result set
st.add(curr.join(''));
return;
}
for (let j = 0; j < s.length; j++) {
if (!used[j]) {
// Mark the character as used
used[j] = true;
curr.push(s[j]);
// Recurse with the next character
genPermutation(i + 1, s, used, curr, st);
// Backtrack and unmark the character
used[j] = false;
curr.pop();
}
}
}
function findPermutation(s) {
// To track if a character is used
let used = Array(s.length).fill(false);
let st = new Set();
let curr = [];
// Start the recursion
genPermutation(0, s, used, curr, st);
// Convert the set to an array
return Array.from(st);
}
// Driver Code
let s = "ABC";
let res = findPermutation(s);
// Print the permutations
console.log(res.join(' '));
OutputCBA BAC CAB BCA ABC ACB
Time Complexity: O(n*n!), where n is the size of the array.
Auxiliary Space: O(n!), space used by hash set.
[Expected Approach] Generating Only Unique Permutations
This approach is similar to generating all possible permutation. Now in this approach, while generating the permutations, at each index during recursion, we only consider the unique available characters. To track the availability of characters we use hash map.
Duplicate permutations are generated in the previous approach because it treats identical characters, like the two 'B's in "ABBC," as distinct due to their indices. For example, when placing a 'B' at an index, choosing the first or second 'B' results in the same permutation (e.g., "ABBC" or "ABBC" again), leading to duplicates.
In this approach, we prune branches in the recursive tree that would generate duplicate permutations and place only unique available characters at each index.
C++
//C++ program to print unique permutation of string
//using hash map.
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
// Recursive function to generate permutations
void genPermutations(int n, string &curr ,unordered_map<char, int> &cnt,
vector<string>& res) {
// Base case: If the current permutation length equals the input
// string length, add it to the result
if (curr.size() == n) {
res.push_back(curr);
return;
}
// Iterate through each character in the frequency map
for (pair<char, int> it: cnt) {
char c = it.first;
int count = it.second;
// Skip characters with a count of 0
if (count == 0)
continue;
// Include the character in the current permutation
curr.push_back(c);
// Decrease its count in the frequency map
cnt[c]--;
// Recur to build the next character in the permutation
genPermutations(n, curr, cnt , res);
// Backtrack: Remove the character and restore its count
curr.pop_back();
cnt[c]++;
}
}
// Function to find all unique permutations of the input string
vector<string> findPermutation(string s) {
// Vector to store the result
vector<string> res;
// Frequency map to count occurrences of each character
unordered_map<char, int> cnt;
// Populate the frequency map with the characters of the input string
for (char c : s)
cnt[c]++;
// To build permutations
string curr = "";
genPermutations(s.size(), curr, cnt, res);
return res;
}
int main() {
string s = "ABC";
vector<string> res = findPermutation(s);
for (string perm: res)
cout << perm << " ";
return 0;
}
Java
//Java program to print unique permutation of string
//using hash map.
import java.util.*;
class GfG {
// Recursive function to generate permutations
static void genPermutations(int n, StringBuilder curr,
Map<Character, Integer> cnt, List<String> res) {
// Base case: If the current permutation length equals
// to the input string length, add it to the result
if (curr.length() == n) {
res.add(curr.toString());
return;
}
// Iterate through each character in the frequency map
for (Map.Entry<Character, Integer> entry : cnt.entrySet()) {
char c = entry.getKey();
int count = entry.getValue();
// Skip characters with a count of 0
if (count == 0)
continue;
// Include the character in the current permutation
curr.append(c);
// Decrease its count in the frequency map
cnt.put(c, count - 1);
// Recur to build the next character in the permutation
genPermutations(n, curr, cnt, res);
// Backtrack: Remove the character and restore its count
curr.deleteCharAt(curr.length() - 1);
cnt.put(c, count);
}
}
// Function to find all unique permutations of the input string
static ArrayList<String> findPermutation(String s) {
ArrayList<String> res = new ArrayList<>();
// Frequency map to count occurrences of each character
Map<Character, Integer> cnt = new HashMap<>();
// Populate the frequency map with the characters of the input string
for (char c : s.toCharArray())
cnt.put(c, cnt.getOrDefault(c, 0) + 1);
// To build permutations
StringBuilder curr = new StringBuilder();
genPermutations(s.length(), curr, cnt, res);
return res;
}
public static void main(String[] args) {
String s = "ABC";
List<String> res = findPermutation(s);
for (String perm : res)
System.out.print(perm + " ");
}
}
Python
#C++ program to print unique permutation of string
#using hash map.
# Recursive function to generate permutations
def genPermutations(n, curr, cnt, res):
# Base case: If the current permutation length equals
# the input string length, add it to the result
if len(curr) == n:
res.append(curr)
return
# Iterate through each character in the frequency map
for c, count in cnt.items():
# Skip characters with a count of 0
if count == 0:
continue
# Include the character in the current permutation
cnt[c] -= 1
# Recur to build the next character in the permutation
genPermutations(n, curr + c, cnt, res)
# Backtrack: Restore the count
cnt[c] += 1
# Function to find all unique permutations of the input string
def findPermutation(s):
# List to store the result
res = []
# Frequency map to count occurrences of each character
cnt = {}
# Populate the frequency map with the characters of the input string
for c in s:
cnt[c] = cnt.get(c, 0) + 1
# Generate permutations
genPermutations(len(s), "", cnt, res)
return res
if __name__ == "__main__":
s = "ABC"
res = findPermutation(s)
print(" ".join(res))
C#
// C# program to print unique permutation of string
// using hash map.
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to generate permutations
static void genPermutations(int n, string curr,
Dictionary<char, int> cnt, List<string> res) {
// Base case: If the current permutation length equals the input
// string length, add it to the result
if (curr.Length == n) {
res.Add(curr);
return;
}
// Iterate through a copy of the dictionary's keys
foreach (char c in new List<char>(cnt.Keys)) {
int count = cnt[c];
// Skip characters with a count of 0
if (count == 0)
continue;
// Include the character in the current permutation
curr += c;
// Decrease its count in the frequency map
cnt[c]--;
// Recur to build the next character in the permutation
genPermutations(n, curr, cnt, res);
// Backtrack: Remove the character and restore its count
curr = curr.Remove(curr.Length - 1);
cnt[c]++;
}
}
// Function to find all unique permutations of the input string
static List<string> findPermutation(string s) {
// List to store the result
List<string> res = new List<string>();
// Frequency map to count occurrences of each character
Dictionary<char, int> cnt = new Dictionary<char, int>();
// Populate the frequency map with the characters of the input string
foreach (char c in s) {
if (cnt.ContainsKey(c))
cnt[c]++;
else
cnt[c] = 1;
}
// To build permutations
string curr = "";
genPermutations(s.Length, curr, cnt, res);
// Convert the result list to an array
return res;
}
static void Main(string[] args) {
string s = "ABC";
List<string> res = findPermutation(s);
foreach (string perm in res)
Console.Write(perm + " ");
}
}
JavaScript
//javascript program to print unique permutation of string
//using hash map.
// Recursive function to generate permutations
function genPermutations(n, curr, cnt, res) {
// Base case: If the current permutation length equals
// the input string length, add it to the result
if (curr.length === n) {
res.push(curr);
return;
}
// Iterate through each character in the frequency map
for (let c in cnt) {
if (cnt[c] === 0)
continue;
// Include the character in the current permutation
cnt[c]--;
// Recur to build the next character in the permutation
genPermutations(n, curr + c, cnt, res);
// Backtrack: Restore the count
cnt[c]++;
}
}
// Function to find all unique permutations of the input string
function findPermutation(s) {
// Array to store the result
const res = [];
// Frequency map to count occurrences of each character
const cnt = {};
// Populate the frequency map with the characters of the input string
for (const c of s)
cnt[c] = (cnt[c] || 0) + 1;
// Generate permutations
genPermutations(s.length, "", cnt, res);
return res;
}
// Driver code
const s = "ABC";
const res = findPermutation(s);
// Print the permutations
console.log(res.join(" "));
OutputCBA CAB BCA BAC ACB ABC
Time Complexity: O(n*n!), In worst case all characters were unique, so it take time equal to generating all permutations.
Auxiliary Space: O(n), used by temporary string and hash map.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem