Lexicographic rank of a string among all its substrings | Function to find lexicographic rank of string among all its substring ; Length of string ; Traverse the given string and store the indices of each character ; Extract the index ; Store it in the vector ; Traverse the alphaIndex array lesser than the index of first character of given string ; If alphaIndex [ i ] size exceeds 0 ; Traverse over the indices ; Add count of substring equal to n - alphaIndex [ i ] [ j ] ; Store all substrings in a vector str starting with the first character of the given string ; Insert the current character to substring ; Store the substring formed ; Sort the substring in the lexicographical order ; Find the rank of given string ; increase the rank until the given string is same ; If substring is same as the given string ; Add 1 to rank of the given string ; Given string ; Function Call
function lexicographicRank ( s ) { var n = s . length ; var alphaIndex = Array . from ( Array ( 26 ) , ( ) => new Array ( ) ) ; for ( var i = 0 ; i < s . length ; i ++ ) { var x = s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; alphaIndex [ x ] . push ( i ) ; } var rank = 0 ; for ( var i = 0 ; i < 26 && ' ' . charCodeAt ( 0 ) + i < s [ 0 ] . charCodeAt ( 0 ) ; i ++ ) { if ( alphaIndex [ i ] . length > 0 ) { for ( var j = 0 ; j < alphaIndex [ i ] . length ; j ++ ) { rank = rank + ( n - alphaIndex [ i ] [ j ] ) ; } } } var str = [ ] ; for ( var i = 0 ; i < alphaIndex [ s [ 0 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] . length ; i ++ ) { var substring = " " ; var j = alphaIndex [ s [ 0 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] [ i ] ; for ( ; j < n ; j ++ ) { substring += ( s [ j ] ) ; str . push ( substring ) ; } } str . sort ( ) ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] != s ) { rank ++ ; } else { break ; } } return rank + 1 ; } var str = " " ; document . write ( lexicographicRank ( str ) ) ;