Print all the permutations of a string without repetition using Collections 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. A permutation should not have repeated strings in the output.

Examples:

Input: str = “aa”
Output:
aa
Note that “aa” will be printed only once
as duplicates are not allowed.



Input: str = “ab”
Output:
ab
ba

Approach: Write a recursive function that removes a character one by one from the original string and generates a new string by appending these removed characters. The base condition will be when all the characters have been used. In that case, insert the generated string (a permutation of the original string) in a set in order to avoid duplicates.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
public class GFG {
  
    static Set<String> hash_Set = new HashSet<>();
  
    // Recursive function to generate
    // permutations of the string
    static void Permutation(String str, String ans)
    {
  
        // If string is empty
        if (str.length() == 0) {
  
            // Add the generated permutation to the
            // set in order to avoid duplicates
            hash_Set.add(ans);
            return;
        }
  
        for (int i = 0; i < str.length(); i++) {
  
            // ith character of str
            char ch = str.charAt(i);
  
            // Rest of the string after excluding
            // the ith character
            String ros = str.substring(0, i)
                         + str.substring(i + 1);
  
            // Recurvise call
            Permutation(ros, ans + ch);
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "ab";
  
        // Generate permutations
        Permutation(s, "");
  
        // Print the generated permutations
        hash_Set.forEach((n) -> System.out.println(n));
    }
}

chevron_right


Output:

ab
ba


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.