Skip to main content

How to find all Permutations and Combinations of a String

Algorithm Used

We will be using the following algorithm to find all the permutations of a string

  • Take the first letter as a prefix and find all the permutations of the remaining string.
  • Each of the prefix will also be a permutation itself.
  • If you want to find all the permutations of string with same length as the original string then skip the prefix's as the combination.

public class Permute {

static String codes = "eki";
static int count;
public static void main(String args[]) {
permute("", codes);
System.out.println(">>>>>>>" + count);
}

public static void permute(String prefix, String str) {
System.out.println(prefix);
count++;
int n = str.length();
if (n == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < n; i++)
permute(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}

}

}
The above code will give the following output
e
ek
eki
eki
ei
eik
eik
k
ke
kei
kei
ki
kie
kie
i
ie
iek
iek
ik
ike
ike
>>>>>>>16

Comments