Java Program to Find all Permutations of String

In this post, we will write a Java program to find all permutations of String.
This program provides a easy recursive solution. let's write a program to print all permutations of a String in Java, for example if input is "xyz" then it should print "xyz", "yzx", "zxy", "xzy", "yxz", "zyx".

Java Program to Find all Permutations of String

import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;

/**
 * Java Program to Find all Permutations of String
 * @author javaguides.net
 *
 */
public class StringPermutationsProgram {
 
     public List<String> permutations(String inputStr) {
        if (inputStr == null)
           return null;
  
        final List<String> result = new ArrayList<>();
        if (inputStr.length() < 2) {

            result.add(inputStr);
            return result;
        }

        final List<String> permutations = permutations(inputStr.substring(1));
        for (final String permutation : permutations) {
        for (int i = 0; i <= permutation.length(); i++) {
        String newPermutation = permutation.substring(0, i) 
              + inputStr.charAt(0) + permutation.substring(i);
        result.add(newPermutation);
     }
   }
  return result;
}

 public static void main(String[] args) {
     StringPermutationsProgram permuter = new StringPermutationsProgram();
     List<String> perms = permuter.permutations("xyz");
     System.out.println(Arrays.toString(perms.toArray()));
  
     List<String> perms1 = permuter.permutations("abca");
     System.out.println(Arrays.toString(perms1.toArray()));
   }
}
Output:
[xyz, yxz, yzx, xzy, zxy, zyx]
[abca, baca, bcaa, bcaa, acba, caba, cbaa, cbaa, acab, caab, caab, caba, abac, baac, baac, baca, aabc, 
aabc, abac, abca, aacb, aacb, acab, acba]
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Comments