Print all permutation of a string using ArrayList in Java


In this problem, we are given a string of size n and we have to print all permutations of the string. But this time we have to print this permutation using ArrayList.

Let’s take an example to understand the problem -

Input − string = ‘XYZ’

Output − XYZ, XZY, YXZ, YZX, ZXY, ZYX

To solve this problem, we will be generating all permutations of the character of the string. We will use a recursive function and will return arrayList.

Example

The following is ArrayList implementation of the algorithm −

 Live Demo

import java.util.ArrayList;
public class Main{
   static void printArrayList(ArrayList<String> combo) {
      combo.remove("");
      for (int i = 0; i < combo.size(); i++)
      System.out.print(combo.get(i)+"\t");
   }
   public static ArrayList<String> generatePermutation(String str) {
      if (str.length() == 0) {
         ArrayList<String> empty = new ArrayList<>();
         empty.add("");
         return empty;
      }
      char ch = str.charAt(0);
      String subStr = str.substring(1);
      ArrayList<String> lastCombination = generatePermutation(subStr);
      ArrayList<String> newCombination = new ArrayList<>();
      for (String val : lastCombination) {
      for (int i = 0; i <= val.length(); i++) {
            newCombination.add(val.substring(0, i) + ch + val.substring(i));
         }
       }
      return newCombination;
    }
   public static void main(String[] args) {
      String str = "NOPQ";
      System.out.println("Permutations of string are :");
      printArrayList(generatePermutation(str));
   }
}

Output

Permutations of string are :
NOPQ ONPQ OPNQ OPQN NPOQ PNOQ
PONQ POQN NPQO PNQO PQNO
PQON NOQP ONQP OQNP OQPN
NQOP QNOP QONP QOPN NQPO
QNPO QPNO QPON

Updated on: 14-Jul-2020

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements