For a given string say dbac
the possible substrings are [d,db,dba,dbac,b,ba,bac,a,ac,c]. Sort them and concatenate to a string: aacbbabaccddbdbadbac
. Find the character at index m=2
, so the answer is c
.
Here is my code:
public char solve(String s, int m) {
int n = s.length();
List<String> list = new ArrayList<>();
for(int i=0; i<n; i++) {
for(int j=i+1; j<=n; j++) {
list.add(s.substring(i,j));
}
}
Collections.sort(list);
for(String s1 : list) {
int q = s1.length();
if(m >=q) m -=q;
else {
return s1.charAt(m);
}
}
return ' ';
}
The time complexity of this code is \$O(n^3)\$ because nested for loops and substring methods.
Is there a way to solve this with lower time complexity?