How to Find All Permutations of String in Java using Recursion? Solution Example (original) (raw)

How to find all permutations of a String using recursion is one of the tricky coding questions from programming job interviews. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better java programming exercise for beginners.

Typically, you will be asked to write a method, which accepts a String and print all permutations or may return all permutations in a List for a junior developer position. Depending upon the company you are going for an interview, they may ask you to code on IDE like Eclipse or NetBeans, or simply write code in plain paper, so be prepared for both.

There are two main ways to solve this problem, using loops or by using recursion, the second one is what the interviewer expects.

Since recursion is a tricky programming concept to master, it's not easy for every programmer to solve this problem on the fly, especially if you are not coding on a daily basis or don't have that highly sought-after code sense.

Solution 1 - Final All Permutations of given String Using Recursion and Loop

Now let's get back to the problem, Permutation refers to the ordering of characters but it takes position into account i.e. if you have String "ab" then it will have just 2 permutations "ab" and "ba", because the position of the character in both Strings is different.

Similarly for a String of n characters there are !n (factorial of n) permutations are possible e.g. for a String of 3 characters like "xyz" has 6 possible permutations, xyz, xzy, yxz, yzx, zxy, zyx as seen in our example.

As I told you there are two ways to solve this problem either by using for loop (iterative algorithm) or by using recursion, but the most elegant solution is a combination of both loop and recursion.

If you remember the factorial problem you know that factorial is naturally recursive i.e. factorial of n is nothing but n * factorial of n -1. Similarly, permutations are also a recursive problem e.g. permutation of n characters is nothing but fixing one character and calculating permutation of n - 1 characters e.g. in the case of "xyz", you can fix "x" and calculate permutation of "yz".

In order to calculate all permutations of a String, you need to repeat this exercise for all characters one at a time. This is where for loop comes into the picture. So, this solution uses both for loop and recursion to print all permutations of a given String.

In the case of recursion, the most important question is the base case, because that is responsible for stopping recursive calls. If you don't have a base case then your program will eventually terminate with java.lang.StackOverFlowError.

In this problem, our base case is a permutation of empty String, which is nothing but the empty String itself. After each call, the problem set is reduced and inches towards the base case, when it reaches there stack starts rolling down and calculates the result.

Java Program to Print All Permutation of a String

Here is our sample Java program to print all permutations of a given string using a recursive algorithm. It uses both loop and a recursive call to solve this problem. It also demonstrates a technique of hiding your implementation detail using a private method and exposing a much cleaner public method as API. In our solution, we have two permutation methods, one is public, and the other is private.

The first method is clean and exposed to the client but the second method requires you to pass an empty string as the initial value of the perm parameter which is used to store the intermediate permutation of String.

If you expose this method to the client then it will wonder about this empty String, since it's part of the implementation, it's better to hide and get rid of it as soon as you have a better algorithm to solve this problem, how about taking it as an exercise?

/**

/*

}

/* * Recursive method which actually prints all permutations * of given String, but since we are passing an empty String * as current permutation to start with, * I have made this method private and didn't exposed it to client. */ private static void permutation(String perm, String word) { if (word.isEmpty()) { System.err.println(perm + word);

    } else {
        for (int i = 0; i < word.length(); i++) {
            permutation(perm + word.charAt(i), word.substring(0, i) 
                            + word.substring(i + 1, word.length()));
        }
    }

}

}

Output: 123 132 213 231 312 321

Like everything else, practice is your friend, doing this kind of coding exercise on a daily basis, solving programming puzzles, and doing more complex programs available on internet sites like project Euler, TopCoder will help you to build confidence in your coding and problem-solving skill.

You can also take the help of some classic coding interview courses and books like Cracking the Coding interview to do well on coding interviews

Java Program to find all permutation of String

Explanation of Code :

All code for calculating permutation of String is inside permutation(String perm, String word) method, I have purposefully made this method private because of additional parameter I am passing as an initial value of permutation.

This demonstrates a technique of hiding implementation detail from a client and exposing a much cleaner API to the client e.g. just permutation(String input) method, passing empty String is an implementation detail and ugly for a client to pass whenever it needs to calculate permutation. It is also an exercise for you to see if you can improve the code by getting rid of that empty String.

The algorithm is nothing but keeping one character fix and then calculating permutations of others. The crux of the program is in the following code segment :

for (int i = 0; i < word.length(); i++) { permutation(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1, word.length())); }

Here we have a for loop to go through each character of String e.g. for input "123" this loop will run three times. In each iteration, we are making a recursive call to function itself i.e. permutation(String perm, String word) method, where the first parameter is used to store the result.

After 1st iteration perm (first parameter of permutation() method) will be "" + 1 as we are doing word.charAt(i) and i is zero. Next, we take out that character and pass the remaining characters to the permutation method again e.g. "23" in the first iteration.

The recursive call ends when it reaches to base case i.e. when the remaining word becomes empty, at that point "perm" parameter contains a valid permutation to be printed. You can also store it into a List if you want to.

Here is a nice diagram that visually shows what this algorithm does :

Print all permutation of a String in Java example

That's all on how to find all permutations of a String in Java using recursion. It's a very good exercise for preparing Java coding interviews. Why not you give it a try and come up with another solution? also could you calculate the complexity of this algorithm, to it looks n*!n because the loop will run for n times, and for each n, we will call the permutation method.

Also, how about writing some JUnit test cases to see if this solution works for various inputs e.g. empty String, one letter String, many letters String, String with duplicate characters, etc? It's a good practice to become hands-on in writing JUnit tests.

If you are interested in more of such coding questions, you can check the following interview questions collected from various Java interviews :

And, now is the quiz time, which one is your favorite string based coding problems? counting occurance of characters, palindrom, reverse a String, finding duplicates or this one?