Count number of distinct substrings of a given length | Javascript implementation of above approach ; Function to find the required count ; Variable to the hash ; Finding hash of substring ( 0 , l - 1 ) using random number x ; Computing x ^ ( l - 1 ) ; Unordered set to add hash values ; Generating all possible hash values ; Print the result ; Driver Code
var x = 26 ; var mod = 3001 ; function CntSubstr ( s , l ) { var hash = 0 ; for ( var i = 0 ; i < l ; i ++ ) { hash = ( hash * x + ( s [ i ] . charCodeAt ( 0 ) - 97 ) ) % mod ; } var pow_l = 1 ; for ( var i = 0 ; i < l - 1 ; i ++ ) pow_l = ( pow_l * x ) % mod ; var result = new Set ( ) ; result . add ( hash ) ; for ( var i = l ; i < s . length ; i ++ ) { hash = ( ( hash - pow_l * ( s [ i - l ] . charCodeAt ( 0 ) - 97 ) + 2 * mod ) * x + ( s [ i ] . charCodeAt ( 0 ) - 97 ) ) % mod ; result . add ( hash ) ; } document . write ( result . size ) ; } var s = " " ; var l = 2 ; CntSubstr ( s , l ) ;