Find all Permutations of a String in java

In this post, we will see how to find all permutations of String in java.
We will use a very simple approach to do it.

Take out first character of String and insert into different places of permutations of remaining String recursively.

Lets say you have String as ABC.
So we take out A from ABC
First character =A and RemainingString = BC 
As we are applying recursion here, we will find permutations of BC.
Take out B from BC.
First character= B and RemainingString = C 
As we are applying recursion here, we will find permutations of C.
When we take out C, our String size becomes 0 and that is our base case here.
First character = C and RemainingString = “” 
We insert C to differences indexes of Permutations  of RemainingString(“”), so we get permutation of C as C.
We insert B to different indexes of Permutations of remainingString(C), so we get BC and CB.
C: BC, CB
Now we insert A to different indexes in BC and CB.
BC : ABC , BAC , BCA
CB : ACB, CAB, CBA
so thats how we got all permutations of ABC.
It may look tricky but once you practice the solution, you will be able to understand it better.

Java program to find all Permutations of String in java:

When you run above program, you will get following out:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *