Sitemap
Ashmeet Kaur

Ashmeet Kaur

Writing articles on core Java Development .

Permutation of String without using Recursion

2 min readJan 12, 2023

Here we are given a String abc .We need to find the permutation of a String.

Lets understand how we can find the permutation.
1).We have abc
2)We know that the permutation of the string will be n!.
3).So here the length of the string is 3.hence 6 permutation will be there .

Get Ashmeet Kaur’s stories in your inbox

Join Medium for free to get updates from this writer.

Firstly understand this point -
We have 6 permutation here for abc-
a)0 to 6
i).for 0,1,2-if we divide it by three,we will get 0 right.
ii).for 3,4,5,if we divide it by 3 we will get 1 right
Lets take another exmple
We have abcd as string and 24 as permutation
i).for 0,1,2,3- if we divide it by 4 we get 0.
ii).for 4,5,6,7.if we divide it by 4, we get 1.
iii).for 8,9,10,11 if we divide by 4,we get 2.
iv).for 12,13,14,15,if we divide by 4,we get 3.
v)for 16,17,18,19,if we divide by 4,we get 4
vi)for 20,21,22,23 ifwe divide by 4,we get 5.

Lets understand this
for abc
1).Suppose we have taken a ,a need to be removed right,and we should take the next element ie b.and then after removing b we should be taking the 0th element ie c.(for permutation number 0)
so abc will be printed.
2).Now We have taken b,now b has to be removed but we will be taking the 0th element only after removing b,ie a and after removing a the 0th elemnt will be c.
bca.
3).Now we have taken c,now c need to be removed ,but after removing c ,we should be printing 0th element only.
cab.
4).Now when permutation becomes 4 We know that now after division we will be getting 1 .So we willbe taking the 1th index after removing any index.
So this way every index willbe covered.

import java.io.*;
import java.util.*;

public class Main {

public static void solution(String str){

int permutation=1;
int i=0;
int j=0;
for(i=str.length();i>0;--i)
{
permutation=permutation*i;

}



for(i=0;i<permutation;++i)
{
StringBuilder str1=new StringBuilder(str);
int temp=i;
for(j=str1.length();j>0;--j)
{

int rem=temp%j;
int quo=temp/j;
System.out.print(str1.charAt(rem));
str1.deleteCharAt(rem);
temp=quo;

}
System.out.println();
}


}
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
String str = scn.next();
solution(str);
}

}

--

--

Ashmeet Kaur
Ashmeet Kaur

Written by Ashmeet Kaur

Writing articles on core Java Development .