Print All The Permutations Of a String

Objective: Given a String, print all the permutations of it.

Input: A String

Output: Print all the permutations of a string

Example:

Input : abc
Output: abc acb bac bca cba cab

Approach:
  • Take one character at a time and fix it at the first position. (use swap to put every character at the first position)
  • make recursive call to rest of the characters.
  • use swap to revert the string back to its original form fo next iteration.

Permutations

Complete Code:

import java.util.*;
import java.lang.*;
import java.io.*;
public class StringPermutations {
private char[] arrA;
public void permutation(char[] arrA, int left, int size) {
int x;
if (left == size) {
for (int i = 0; i < arrA.length; i++) {
System.out.print(arrA[i]);
}
System.out.print(" ");
} else {
for (x = left; x < size; x++) {
swap(arrA, left, x);
permutation(arrA, left + 1, size);
swap(arrA, left, x);
}
}
}
public void swap(char[] arrA, int i, int j) {
char temp = arrA[i];
arrA[i] = arrA[j];
arrA[j] = temp;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
String s = "abc";
char[] arrCh = s.toCharArray();
StringPermutations i = new StringPermutations();
i.permutation(arrCh, 0, arrCh.length);
}
}

Output :

abc acb bac bca cba cab

4 thoughts on “Print All The Permutations Of a String”

  1. use simple string based program as below

    public class StringPermutations {

    public static void main(String[] args) {

    String s = “abcd”;

    StringPermutations i = new StringPermutations();

    i.permute(“”, s);

    }

    private void permute(String newString, String oriString) {

    if (oriString == null || oriString.isEmpty()) {

    System.out.println( newString);

    }

    for (int i = 0; i < oriString.length(); i++) {

    permute(newString.concat(oriString.substring(i, i + 1)), oriString

    .substring(0, i).concat(oriString.substring(i + 1)));

    }

    }

    }

    Reply
  2. Hello Team,

    It is a nice work.

    One suggestion to this post: We do not need second swap and when left and size are equal then just print the string. we do need to iterate with for loop

    Reply

Leave a Reply to sanjib Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.