Given a string str, the task is to print all the distinct 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 letter word.
Input: str = “abbb”
Output: [abbb, babb, bbab, bbba]
Input: str = “abc”
Output: [abc, bac, bca, acb, cab, cba]
Approach: Write a recursive function that will generate all the permutations of the string. Terminating condition will be when the passed string is empty, in that case the function will return an empty ArrayList. Before adding the generated string, just check if it has already been generated before to get the distinct permutations.
Below is the implementation of the above approach:
[abbb, babb, bbab, bbba]
Optimization : We can optimize above solution to use HashSet to store result strings in place of Res ArrayList.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print all distinct permutations of a given string with duplicates
- Print first n distinct permutations of string using itertools in Python
- Iterative program to generate distinct Permutations of a String
- Distinct permutations of a string containing duplicates using HashSet in Java
- Java Program to print all permutations of a given string
- Print distinct sorted permutations with duplicates allowed in input
- Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
- Count of distinct permutations of every possible length of given string
- Distinct permutations of the string | Set 2
- Write a program to print all permutations of a given string
- Print all permutations of a string in Java
- Print all the permutations of a string without repetition using Collections in Java
- Count of distinct permutations of length N having no similar adjacent characters
- Print all palindrome permutations of a string
- Print all the palindromic permutations of given string in alphabetic order
- Print all lexicographical greater permutations of a given string
- Find distinct characters in distinct substrings of a string
- Find Kth largest string from the permutations of the string with two characters
- Java Program for Anagram Substring Search (Or Search for all permutations)
- Print all permutations with repetition of characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.