Sir i am getting a TLE plz tell me what is wrong in my code?

import java.util.*;
public class Main {

    public static ArrayList<String> result;

public static void main(String[] args) {
	Scanner scn = new Scanner(System.in);
	String str = scn.next();
	result = new ArrayList<>();
	permutationprint(str, "");
	for (int p = 0; p < result.size() - 1; p++) {
		for (int q = p + 1; q < result.size(); q++) {
			if (result.get(p).compareTo(result.get(q)) > 0) {
				Collections.swap(result, p, q);

			}
		}
	}
	for (int j = 0; j < result.size(); j++) {
		if (str.compareTo(result.get(j))<=0) {
			return;
		}
		System.out.println(result.get(j));
	}

}

public static void permutationprint(String str, String ans) {

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

		result.add(ans);

		return;

	}

	for (int i = 0; i < str.length(); i++) {
		char ch = str.charAt(i);

		String ros = str.substring(0, i) + str.substring(i + 1);

		permutationprint(ros, ans + ch);
	}


}

}

@harsh.hj,

I see that you have got the correct answer. Any further doubts on this question?

yes plz tell me why i am gettine tle

in this code ,i want to know that how can i optimise this code

@harsh.hj,
You are first generating all the permutations and then sorting them. While sorting you are using O(n^2) complexity in the worst case. Also, you are adding all the permutations, you can add only the required permutations and use a better sorting algorithm.