28
loading...
This website collects cookies to deliver better user experience
Rank of a word is basically deduced from making all combinations of the alphabets from the given word - sorting them in order as in dictionary and checking the position of our given word.
1 : ABLL
2 : ALBL
3 : ALLB
4 : BALL -- this is our desired word
5 : BLAL
6 : BLLA
7 : LABL
8 : LALB
9 : LBAL
10 : LBLA
11 : LLAB
12 : LLBA
4!=24
. 6!/2! = 360
. {A, I, N, R}
and the letters of the word “soccer” shall be arranged as {C,C,E,O,R,S}
. It shall be noted that since C appeared two times in soccer, it shall be written two times here also. This is your second step.{A,I,N,R}
3!=6
words can be formed, none of them being rain, since rain starts with R and not I. Safe to say the rank of the word is nowhere from 7 to 12. (Agree?)Rain
Rani
Rian
Rina
Rnai
Rnia
{C,C,E,O,R,S}
5!=120
words. But none of these words can be soccer, since soccer starts with S and not C. So, you can be pretty sure that the rank is nowhere between 1 to 120. (Agree?)5!/2!=60
, none of which can be soccer. Thus, no rank from 121 to 180.{C,C,E,O,R}
. Pick C as the second letter and 4!=24
words now start with SC. No word possible from 301 to 324. 4!/2! = 12
-> Similarly, rank 325 to 336 is taken by SE. public static long findRank(String word) {
long rank = 1;
long suffixPermCount = 1;
final Map<Character, Integer> charCounts = new HashMap<>();
for (int i = word.length() - 1; i >= 0; i--) {
char x = word.charAt(i);
int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;
charCounts.put(x, xCount);
for (Map.Entry<Character, Integer> e : charCounts.entrySet()) {
if (e.getKey() < x) {
rank += suffixPermCount * e.getValue() / xCount;
}
}
suffixPermCount *= word.length() - i;
suffixPermCount /= xCount;
}
return rank;
}