Count number of distinct substrings of a given length | C ++ 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
#include <bits/stdc++.h> NEW_LINE #define x  26 NEW_LINE #define mod  3001 NEW_LINE using namespace std ; int CntSubstr ( string s , int l ) { int hash = 0 ; for ( int i = 0 ; i < l ; i ++ ) { hash = ( hash * x + ( s [ i ] - 97 ) ) % mod ; } int pow_l = 1 ; for ( int i = 0 ; i < l - 1 ; i ++ ) pow_l = ( pow_l * x ) % mod ; unordered_set < int > result ; result . insert ( hash ) ; for ( int i = l ; i < s . size ( ) ; i ++ ) { hash = ( ( hash - pow_l * ( s [ i - l ] - 97 ) + 2 * mod ) * x + ( s [ i ] - 97 ) ) % mod ; result . insert ( hash ) ; } cout << result . size ( ) << endl ; } int main ( ) { string s = " abcba " ; int l = 2 ; CntSubstr ( s , l ) ; return 0 ; }