# Count distinct substrings of a string using Rabin Karp algorithm

Given a string, count the number of distinct substrings using Rabin Karp Algorithm.

**Examples**:

Input: str = “aba”Output: 5Explanation: Total number of distinct substring are 5 - "a", "ab", "aba", "b" ,"ba"Input: str = “abcd”Output: 10Explanation: Total number of distinct substring are 10 - "a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd", "d"

**Approach:**

**Prerequisite**: Rabin-Karp Algorithm for Pattern Searching

Calculate the current hash value of the current character and store

in a dictionary/map to avoid repetition.

To compute the hash (rolling hash) as done in Rabin-Karp algorithm follow:

The hash function suggested by Rabin and Karp calculates an integer value. The integer value for a string is numeric value of a string. For example, if all possible characters are from 1 to 10, the numeric value of “122” will be 122. The number of possible characters is higher than 10 (256 in general) and pattern length can be large. So the numeric values cannot be practically stored as an integer. Therefore, the numeric value is calculated using modular arithmetic to make sure that the hash values can be stored in an integer variable (can fit in memory words). To do rehashing, we need to take off the most significant digit and add the new least significant digit for in hash value. Rehashing is done using the following formula.

*hash( txt[s+1 .. s+m] ) = ( d ( hash( txt[s .. s+m-1]) – txt[s]*h ) + txt[s + m] ) mod q*

*hash( txt[s .. s+m-1] )* : Hash value at shift *s*.*hash( txt[s+1 .. s+m] )* : Hash value at next shift (or shift *s*+1)*d*: Number of characters in the alphabet*q*: A prime number*h: d^(m-1)*

The idea is similar as we evaluate a mathematical expression. For example, we have a string of “1234” let we compute the value of the substring “12” is 12 and we want to compute the value of the substring “123” this can be calculated as ((12)*10+3)=123, similar logic is applied here.

## Python3

`# importing libraries` `import` `sys` `import` `math as mt` `t ` `=` `1` `# store prime to reduce overflow` `mod ` `=` `9007199254740881` `for` `___ ` `in` `range` `(t):` ` ` `# string to check number of distinct substring` ` ` `s ` `=` `'abcd'` ` ` `# to store substrings` ` ` `l ` `=` `[]` ` ` `# to store hash values by Rabin Karp algorithm` ` ` `d ` `=` `{}` ` ` `for` `i ` `in` `range` `(` `len` `(s)):` ` ` `suma ` `=` `0` ` ` `pre ` `=` `0` ` ` `# Number of input alphabets` ` ` `D ` `=` `256` ` ` `for` `j ` `in` `range` `(i, ` `len` `(s)):` ` ` `# calculate new hash value by adding next element` ` ` `pre ` `=` `(pre` `*` `D` `+` `ord` `(s[j])) ` `%` `mod` ` ` `# store string length if non repeat` ` ` `if` `d.get(pre, ` `-` `1` `) ` `=` `=` `-` `1` `:` ` ` `l.append([i, j])` ` ` `d[pre] ` `=` `1` ` ` `# resulting length` ` ` `print` `(` `len` `(l))` ` ` `# resulting distinct substrings` ` ` `for` `i ` `in` `range` `(` `len` `(l)):` ` ` `print` `(s[l[i][` `0` `]:l[i][` `1` `]` `+` `1` `], end` `=` `" "` `)` |

**Output**

10 a ab abc abcd b bc bcd c cd d

**Time Complexity:** O(N^{2}), N is the length of string

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend **live classes **with experts, please refer **DSA Live Classes for Working Professionals **and **Competitive Programming Live for Students**.