Wrong answer for 4th test case and some more doubts

what should be the output on console if the input is “cba” as it is last word in accordance with dictionary order? My code is giving correct answer for the first 3 test cases and wrong answer for the 4th test case.
CODE:
import java.util.*;
public class Main {
public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();

    ArrayList<String> ans = getPermutation(str);
    Collections.sort(ans);

    for(int i = 0; i < ans.size(); i++) {
        if ((int) ans.get(i).charAt(0) >= (int) str.charAt(0) && ans.get(i).equals(str) == false)
            System.out.println(ans.get(i));

    }
}

public static ArrayList<String> getPermutation(String str) {

    if(str.length() == 0) {
        ArrayList<String> br = new ArrayList<String>();
        br.add("");
        return br;
    }

    char cc = str.charAt(0);
    String ros = str.substring(1);

    ArrayList<String> mr = new ArrayList<String>();

    ArrayList<String> rr = getPermutation(ros);

    for(String rrs : rr) {

        for(int i = 0; i <= rrs.length(); i++) {
            String element = rrs.substring(0, i) + cc + rrs.substring(i);
            mr.add(element);
        }
    }
    return mr;
}

}

Hi @Navneet01,your code was having a very slight error that was you dont have to put the equal to sign when you were checking ans.get(i).charAt(0)>=str.charAt(0).
I have made that change for you

1 Like