Challenges recursion

sir in one of the test case m getting TLE

have a look plz

import java.util.Scanner;

import java.util.ArrayList;
public class Main{
static Scanner s=new Scanner(System.in);
public static void main(String[] args) {
String str=s.nextLine();
ArrayList permutations = per(str);
larger(permutations ,str);
// for(int i=0 ;i < ans.size();i++) {
// System.out.println(ans.get(i));
// }
}
public static ArrayList per(String str){
if(str.length() == 0) {
ArrayList br=new ArrayList<>();
br.add("");
return br;
}
char ch = str.charAt(0);
String ros = str.substring(1);
ArrayList recres =per(ros);
ArrayList myres =new ArrayList<>();
for(String ss : recres) {
for(int i=0 ;i <=ss.length() ; i++) {
myres.add(ss.substring(0,i) + ch +ss.substring(i));

	}
}
return myres;

}
public static void larger(ArrayList permutations ,String str){

 int len = permutations.size();

ArrayList ans =new ArrayList<>();
for(int i =0 ; i<len ;i++ ) {

	if(permutations.get(i).compareTo(str) >0) {
		ans.add(permutations.get(i));
	}
}

int length =ans.size();
ArrayList<String> answer =new ArrayList<>();
for(int i= 0;i<length ;i++) {
	int min=0;
	for(int j=1 ;j<ans.size();j++) {
		if(ans.get(min).compareTo(ans.get(j)) > 0) {
			min=j;
		}
	}
    //    answer.add(ans.remove(min)); 
	System.out.println( ans.remove(min) );
}

// for(int i=0 ;i<length ;i++) {
// System.out.println(answer.get(i));
// }
}
}

@sameeksha,
The problem is exactly similar to the one in which you are generating all of the permutations of given string and all you need to do is to keep track of the original String too and in the base case just check the answer to be printed must be larger than original String.

So to avoid TLE, you can sort the characters in the string. For example if str = cab, after sorting str = abc and keep original = cab. Now print all permutations which are lexicographically greater than “cab”.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.