Java program to Find Permutations of a Given String

Java program to Find Permutations of a Given String thumbnail
19K
By Dhiraj Ray 01 January, 2018

Description

Write a java program to find all the permutations of any given string. Permutation is the each of several possible ways in which a set or number of things can be ordered or arranged. Order matters in case of Permutation. For example, the permutation of ab will be ab and ba. A string of length n can have a permutations of n!. Following is the java program to find permutation of a given string.

The approach would be to take out the first char and keep it constant and permute the rest of the characters and use recursion to permute the rest of the string except the first character. While making the recursive call, we accumulate each character being constant along with recursive call response.

StringPermutations.java
package com.devglan;

import java.util.ArrayList;
import java.util.List;

public class StringPermutations {

    public List getPermutations(String input) {

        List strList = new ArrayList<>();
        permutations("", input, strList);
        return strList;
    }

    public void permutations(String consChars, String input, List list) {

        if(input.isEmpty()) {
            list.add(consChars + input);
            return;
        }

        for(int i = 0; i < input.length(); i++) {
            permutations(consChars + input.charAt(i),
                    input.substring(0, i)+input.substring(i+1), list);
        }
    }

    public static void main(String a[]) {
        StringPermutations permutations = new StringPermutations();
        List output = permutations.getPermutations("india");
        System.out.println("Result size: "+output.size());
        output.stream().forEach(System.out::println);
    }


}

Explanation

As discussed above, the approach would be to take out the first char and keep it constant and permute the rest of the characters. Assuming abc as the input, the for-each loop equals the length of String. For i = 0, the first constant char would be a and then we get into recursion for "" + bc(input.substring(0, i)+input.substring(i+1)).

Similarly, for i = 1, thew char at index 1(b) will be constant and then we get into recursion with a + c(input.substring(0, i)+input.substring(i+1)).

Below is the recursion tree for abc.

string-permutation-recursive-call
Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.