Implement polynomial rolling hash function for string pattern matching.
Problem Statement
Examples
Input: s = "abc", p = 31, m = 1000000007
Output: 2946
Explanation: Combining the input according to Hashing In Strings | Theory logic yields 2946.
Input: s = "a", p = 31, m = 1000000007
Output: 1
Explanation: Combining the input according to Hashing In Strings | Theory logic yields 1.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Polynomial rolling hash maps strings to integers. Using a prime base p (like 31 or 53) and a large prime modulo m (like 10^9 + 7), each character is weighted by p^i. This enables O(1) comparison of substrings.
Step-by-Step Approach
- Initialize
hash = 0andpPow = 1. - Iterate
ifrom0tos.length - 1. - Value of character:
val = s.charCodeAt(i) - 96. - Accumulate:
hash = (hash + val * pPow) % m. - Advance power:
pPow = (pPow * p) % m. - Return
hash.
Optimal Implementation (JavaScript)
function stringHash(s, p, m) {
let hash = 0;
let pPow = 1;
for (let i = 0; i < s.length; i++) {
hash = (hash + (s.charCodeAt(i) - 96) * pPow) % m;
pPow = (pPow * p) % m;
}
return hash;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single character "a": returns 1.
- Large strings modulo m.