Given a string, your task is to return all its possible permutations in the form of a string array. If the length of input string is greater than 4, return {NULL)



Given a string, your task is to return all its possible permutations in the form of a
string array. If the length of input string is greater than 4, return {NULL)

Example 1: -
Input: hey
Output: {hey, hye, ehy,eyh yeh yne)

Example 2: -
Input: ear
Output: {ear era aer are rae rea)



Here ,I am going to provide a bruteforce solution using neated loops. 

language used :java 

time complexity: O(n^3)

Algo: Bruteforce

Java Solution:- 

import java.util.*;

public class Main

{

public static void main(String[] args) {

    //driver code 

     String str="hey";

    if(str.length()>4){

        System.out.println(" kripya aukaat me rhe ):");

    }

    else{

        System.out.println("iska combination chaiye: "+str );

          System.out.println("ye le phir moz kr : ");

if(str.length()==3){

String [] strArr = getcomb(str,6);;

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

                 System.out.println(strArr[i]);

                }

        }

else{

String [] strArb = getcomb(str,24);;

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

    System.out.println(strArb[i]);

                }}

    }}

public static String[] getcomb(String s,int size){

       int n=s.length();

    String str1[]=new String[size];

    char temp[]=new char[100];

    int r=0;

    for(int i=0;i<n;i++){

        temp[i] =s.charAt(i);

    }

  int j=0,k=0,l=0,m=0;

    if(n>3){

      //just paste this code below in else its same,made minor changes

          for(m=0;m<n;m++){

        for(j=0;j<n;j++){

    for(k=0;k<n;k++){

        for(l=0;l<n;l++){

            if(j==k || k==l || l==j || m==k || m==l || m==j    )

            continue;

          List<Character> char1=Arrays.asList(temp[j],temp[k],temp[l],temp[m]);

   StringBuilder sb= new StringBuilder();

   for(Character ch:char1){

       sb.append(ch);

   } str1[r]=sb.toString();

          r++;

             }

       }

  }}

  }

  else{

  for(j=0;j<n;j++){

    for(k=0;k<n;k++){

        for(l=0;l<n;l++){

            if(j==k || k==l || l==j)

            continue;

         //main part generate combinations and store into string array

         //code by kumarankit3119 

             List<Character> char2=Arrays.asList(temp[j],temp[k],temp[l]);

   StringBuilder sb= new StringBuilder();

   for(Character ch:char2){

       sb.append(ch);

   } str1[r]=sb.toString();

          r++;

          }

       }

  }

  }

       System.out.println( "total combinations:  " +r);

     return str1;

}

}


Post a Comment

0 Comments