Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Combinatorics
  • MCQs on Combinatorics
  • Basics of Combinatorics
  • Permutation and Combination
  • Permutation Vs Combination
  • Binomial Coefficient
  • Calculate nPr
  • Calculate nCr
  • Pigeonhole Principle
  • Principle of Inclusion-Exclusion
  • Catalan Number
  • Lexicographic Rank
  • Next permutation
  • Previous Permutation
Open In App
Next Article:
Print all Unique permutations of a given string.
Next article icon

Distinct permutations of the string | Set 2

Last Updated : 05 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 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"

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(" ")); 

Output
ABC 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:

  • Print all distinct permutations of a given string with duplicates. 
  • Permutations of a given string using STL


Next Article
Print all Unique permutations of a given string.
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Combinatorial
  • DSA
  • Strings
Practice Tags :
  • Combinatorial
  • Strings

Similar Reads

  • Permutations of a given string using STL
    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"
    4 min read
  • Find n-th lexicographically permutation of a string | Set 2
    Given a string of length m containing lowercase alphabets only. We need to find the n-th permutation of string lexicographic ally. Examples: Input: str[] = "abc", n = 3 Output: Result = "bac" All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input: str[] = "aba", n = 2 Output: R
    11 min read
  • Number of distinct permutation a String can have
    We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string. Examples: Input : aab Output : 3 Different permutations are "aab", "aba" and "baa". Input : ybghjhbuytb Output : 1663200 A simple solution is to find a
    6 min read
  • Print all Unique permutations of a given string.
    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: "A
    12 min read
  • Distinct permutations of a number
    Given an integer N, the task is to print all distinct permutations of the number N. Examples: Input: N = 133Output: 133 313 331Explanation:There are a total of 6 permutations, which are [133, 313, 331, 133, 313, 331].Out of all these permutations, distinct permutations are [133, 313, 331]. Input: N
    9 min read
  • All permutations of a string using iteration
    A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
    4 min read
  • Print all permutations of a string in Java
    Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three lett
    3 min read
  • Print first n distinct permutations of string using itertools in Python
    Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated. Examples: Input : string = "abcab", n = 10 Output : aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb Input : string = "okok", n = 4 Output : kkoo koko kook ok
    2 min read
  • Python | Permutation of a given string using inbuilt function
    The task is to generate all the possible permutations of a given string. A permutation of a string is a rearrangement of its characters. For example, the permutations of "ABC" are "ABC", "ACB", "BAC", "BCA", "CAB", and "CBA". The number of permutations of a string with n unique characters is n! (fac
    2 min read
  • Permutations of string such that no two vowels are adjacent
    Given a string consisting of vowels and consonants. The task is to find the number of ways in which the characters of the string can be arranged such that no two vowels are adjacent to each other. Note: Given that No. of vowels <= No. of consonants. Examples: Input: str = "permutation" Output : 9
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences