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.
- Java Program to print all permutations of a given string
- Print all distinct permutations of a given string with duplicates
- Print first n distinct permutations of string using itertools in Python
- Write a program to print all permutations of a given string
- Print all permutations of a string in Java
- Distinct permutations of the string | Set 2
- Print distinct sorted permutations with duplicates allowed in input
- Print all palindrome permutations of a string
- Print all the palindromic permutations of given string in alphabetic order
- Print all distinct characters of a string in order (3 Methods)
- Java Program for Anagram Substring Search (Or Search for all permutations)
- Program to print all substrings of a given string
- Print all permutations with repetition of characters
- Print k different sorted permutations of a given array
- Print all permutations in sorted (lexicographic) order
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.