Related Articles
String hashing using Polynomial rolling hash function
• Difficulty Level : Hard
• Last Updated : 11 Sep, 2020

### What is String-Hashing?

String hashing is the way to convert a string into an integer known as a hash of that string.
An ideal hashing is the one in which there are minimum chances of collision (i.e 2 different strings having the same hash).

### Polynomial rolling hash function

In this hashing technique, the hash of a string is calculated as: Where P and M are some positive numbers.  And s, s, s … s[n-1] are the values assigned to each character in English alphabet (a->1, b->2, … z->26).

Appropriate values for P and M

• P: The value of P can be any prime number roughly equal to the number of different characters used.
For example: if the input string contains only lowercase letters of the English alphabet, then P = 31 is the appropriate value of P.
If the input string contains both uppercase and lowercase letters, then P = 53 is an appropriate option.
• M: the probability of two random strings colliding is inversely proportional to m, Hence m should be a large prime number.
M = 10 ^9 + 9 is a good choice.

Below is the implementation of the String hashing using the Polynomial hashing function:

## C++

 `// C++ implementation of the``// Polynomial Rolling Hash Function` `#include ``using` `namespace` `std;` `// Function to calculate``// the hash of a string``long` `long` `polynomialRollingHash(``    ``string ``const``& str)``{``    ``// P and M``    ``int` `p = 31;``    ``int` `m = 1e9 + 9;``    ``long` `long` `power_of_p = 1;``    ``long` `long` `hash_val = 0;` `    ``// Loop to calculate the hash value``    ``// by iterating over the elements of string``    ``for` `(``int` `i = 0; i < str.length(); i++) {``        ``hash_val``            ``= (hash_val``               ``+ (str[i] - ``'a'` `+ 1) * power_of_p)``              ``% m;``        ``power_of_p``            ``= (power_of_p * p) % m;``    ``}``    ``return` `hash_val;``}` `/// Driver Code``int` `main()``{``    ``// Given strings``    ``string str1 = ``"geeksforgeeks"``;``    ``string str2 = ``"geeks"``;` `    ``cout << ``"Hash of '"` `<< str1 << ``"' = "``         ``<< polynomialRollingHash(str1);``    ``cout << endl;``}`

## Java

 `// Java implementation of the``// Polynomial Rolling Hash Function``class` `GFG{` `// Function to calculate``// the hash of a String``static` `long` `polynomialRollingHash(String str)``{``    ` `    ``// P and M``    ``int` `p = ``31``;``    ``int` `m = (``int``)(1e9 + ``9``);``    ``long` `power_of_p = ``1``;``    ``long` `hash_val = ``0``;` `    ``// Loop to calculate the hash value``    ``// by iterating over the elements of String``    ``for``(``int` `i = ``0``; i < str.length(); i++)``    ``{``        ``hash_val = (hash_val + (str.charAt(i) -``                    ``'a'` `+ ``1``) * power_of_p) % m;``        ``power_of_p = (power_of_p * p) % m;``    ``}``    ``return` `hash_val;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ` `    ``// Given Strings``    ``String str1 = ``"geeksforgeeks"``;``    ``String str2 = ``"geeks"``;` `    ``System.out.print(``"Hash of '"` `+ str1 + ``"' = "` `+``                     ``polynomialRollingHash(str1));``}``}` `// This code is contributed by Amit Katiyar`

## Python3

 `# Python3 implementation of the``# Polynomial Rolling Hash Function` `# Function to calculate``# the hash of a string``def` `polynomialRollingHash(``str``):``    ` `    ``# P and M``    ``p ``=` `31``    ``m ``=` `1e9` `+` `9``    ``power_of_p ``=` `1``    ``hash_val ``=` `0` `    ``# Loop to calculate the hash value``    ``# by iterating over the elements of string``    ``for` `i ``in` `range``(``len``(``str``)):``        ``hash_val ``=` `((hash_val ``+` `(``ord``(``str``[i]) ``-``                                 ``ord``(``'a'``) ``+` `1``) ``*``                              ``power_of_p) ``%` `m)` `        ``power_of_p ``=` `(power_of_p ``*` `p) ``%` `m` `    ``return` `int``(hash_val)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:` `    ``# Given string``    ``str1 ``=` `"geeksforgeeks"` `    ``print``(``"Hash of '{}' = {}"``.``format``(``          ``str1, polynomialRollingHash(str1)))` `# This code is contributed by Shivam Singh`

## C#

 `// C# implementation of the``// Polynomial Rolling Hash Function``using` `System;``class` `GFG{` `// Function to calculate``// the hash of a String``static` `long` `polynomialRollingHash(String str)``{   ``    ``// P and M``    ``int` `p = 31;``    ``int` `m = (``int``)(1e9 + 9);``    ``long` `power_of_p = 1;``    ``long` `hash_val = 0;` `    ``// Loop to calculate the hash value``    ``// by iterating over the elements of String``    ``for``(``int` `i = 0; i < str.Length; i++)``    ``{``        ``hash_val = (hash_val + (str[i] -``                    ``'a'` `+ 1) * power_of_p) % m;``        ``power_of_p = (power_of_p * p) % m;``    ``}``    ``return` `hash_val;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{   ``    ``// Given Strings``    ``String str1 = ``"geeksforgeeks"``;``    ``String str2 = ``"geeks"``;` `    ``Console.Write(``"Hash of '"` `+ str1 + ``"' = "` `+``                   ``polynomialRollingHash(str1));``}``}` `// This code is contributed by 29AjayKumar`
Output:
```Hash of 'geeksforgeeks' = 111226362

```

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.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up