I was writing a code for printing only the lexicographically larger substrings of a string recursively.
static ArrayList<String> getPermutations(String str) {
if (str.length() == 0) {
ArrayList<String> tempArrayList = new ArrayList<String>();
tempArrayList.add("");
return tempArrayList;
}
char currChar = str.charAt(0);
ArrayList<String> resultArrayList = new ArrayList<String>();
ArrayList<String> recResult = getPermutations(str.substring(1));
for (String j : recResult) {
for (int i = 0; i < str.length(); i++) {
resultArrayList.add(j.substring(0, i) + currChar + j.substring(i));
}
}
return resultArrayList;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
ArrayList<String> al = getPermutations(str);
Collections.sort(al);
// System.out.println(al.toString());
int index = al.lastIndexOf(str);
while (index < al.size() - 1) {
System.out.println(al.get(index + 1));
index++;
}
}
The code is working fine. What I've done here is recursively generated all the substrings and simultaneously inserted them in an ArrayList. Later sorted that list, compared the strings and voilà it was done.
Now what is bothering me is the complexity of this program. Here I am generating all the substrings and then choosing from them. For recursion, I feel that it's kind of an automated process, all the substrings will have to be created or visited at least once. So, at this point, I want to ask if this can be optimized like having some kind of check in the recursive function so that only the required substrings (lexicographically larger) are created. If yes, then please elaborate on how to think about it in the case of recursion based solutions.