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:
Hash of 'geeksforgeeks' = 111226362
- What are Hash Functions and How to choose a good Hash Function?
- Rearrange characters in a string such that no two adjacent are same using hashing
- Hash Function for String data in C#
- Complete the sequence generated by a polynomial
- Sgn value of a polynomial
- Program for Derivative of a Polynomial
- Minimize the sum of roots of a given polynomial
- Integration in a Polynomial for a given value
- Content of a Polynomial
- Sorting using trivial hash function
- Address Calculation Sort using Hashing
- Area of the largest square that can be formed from the given length sticks using Hashing
- Implement Phone Directory using Hashing
- Sort elements by frequency | Set 4 (Efficient approach using hash)
- Graph representations using set and hash
- Cryptographic Hash Function in Java
- Convert an array to reduced form | Set 1 (Simple and Hashing)
- Cuckoo Hashing - Worst case O(1) Lookup!
- Top 20 Hashing Technique based Interview Questions
- Hashing | Set 1 (Introduction)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.