Chander Shivdasani Chander Shivdasani - 1 month ago 6x
Java Question

permute a string

Given the String, print all its permutations. To do that, i came up with the following program.

public static char[] swap(char[] input, int i, int j) {
char temp;
temp = input[i];
input[i] = input[j];
input[j] = temp;

return input;


* @param args

public static void permuteStrings(char[] inputString, int start, int finish ) {
//Base case: When there is only single element, print the string
if(start == finish)
else {
//Recursive case: Swap first element with all the elements and permute on the
// rest of string.
for(int i = start; i <= finish; i++) {
inputString = swap(inputString, start, i);
permuteStrings(inputString, i + 1, finish);
inputString = swap(inputString,start, i); //restoring the original string

But, for the given input ABC, all it prints are


I cant seem to figure out what the problem is


Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString, i + 1, finish);.

The correct way was:

permuteStrings(inputString, start + 1, finish);