Implement a polynomial string hash
Challenge · Write code · about 15 min
Compute the polynomial hash of text. Start with h = 0. For each character c, from left to right, set h = (h · 31 + code(c)) mod 1,000,000,007, where code(c) is the character code ('a' is 97).
Return the final h. Reduce h after every character, because the unreduced value overflows quickly.
Example 1
Input:
["cat"]
Output:
98262
99, then 99 · 31 + 97 = 3166, then 3166 · 31 + 116 = 98262.
Example 2
Input:
["ab"]
Output:
3105
"ba" gives 3135, so order matters.
Constraints
- 0 ≤ text.length ≤ 100,000
- text contains lowercase letters a–z only
Learn the idea first: Hash functions: from key to bucket index, a visual lesson.
More Hash functions: from key to bucket index problems
- Bucket for keys Warm-up
- Why mod table size Warm-up
- Predict an anagram's bucket Standard
- Bucket index of every key Standard
- Bucket histogram Standard