Compute and store frequencies for every index
public static void precompute ( String s , String K ) { int n = s . length ( ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { cnt [ i + 1 ] = cnt [ i ] ; if ( s . substring ( i , i + K . length ( ) ) . equals ( K ) ) { cnt [ i + 1 ] += 1 ; } } cnt [ n - 2 + 1 ] = cnt [ n - 2 ] ; }