Doubt regarding Tricky permutations problem

Only 1 test case is failing due to TLE . Can you help me , where should I optimize my code ?

import java.util.*;
public class Main {
public static void main(String args[]) {

	Scanner scan = new Scanner(System.in) ;
	String str = scan.next() ;
	ArrayList<String> ans = new ArrayList<>() ;
	permutations(str,"",ans) ;
	Collections.sort(ans) ;
	for(String val : ans){
		System.out.println(val) ;
	}

}

public static void permutations(String str , String ans , ArrayList<String> al){

	if(str.length() == 1){
		String res = ans+str;
		if(!al.contains(res)){
			al.add(res) ;
		}
		return ;
	}

	for(int i = 0 ; i < str.length() ; i ++){
		permutations(str.substring(0,i)+str.substring(i+1) , ans+str.charAt(i) , al) ;
	}
}

}

@Lalit2142,
Instead of using arraylist use an array and sort the chars in the array before calling the permutations function.

al.contains(): the contains method in arraylist has a worst case time complexity of O(N). reduce that.

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.