Sub topic 3
Hashing a String as a Polynomial
This chapter assumes you know the modulo operator and the modular arithmetic rules from the previous chapter: you can reduce after every addition and multiplication without changing the final remainder. It also assumes you can loop over a string and get each character's code with ord.
The goal is a hash function that turns a string into a single number. Later chapters will update this number in constant time as a window slides. The polynomial hash has that property.
The definition
Treat each character as a digit and the string as a number written in some base b. For a string s of length m, with character codes c0, c1, ..., c(m-1):
H(s) = (c0·b^(m-1) + c1·b^(m-2) + ... + c(m-1)·b^0) mod p
Here b is the base and p is the modulus, usually a large prime. With b = 10 and the digits "472", the formula gives 4·100 + 7·10 + 2 = 472, which is ordinary place value. With b = 256, every byte value fits in one digit position.
The first character gets the highest power. This convention makes the rolling update simple: when the window slides, the leading character is the one you remove.
Why position matters
A plain sum of character codes would give "ab" and "ba" the same hash. Positional weights separate them:
| String | Computation (b = 256) | Hash |
|---|---|---|
| `"ab"` | 97·256 + 98 | 24930 |
| `"ba"` | 98·256 + 97 | 25185 |
Without the modulus, two different strings would always have different numbers, as with any base representation. The modulus keeps the numbers small, and the price is that different strings can now share a hash. That trade-off gets its own chapter.
Computing it with Horner's rule
Computing each b^k separately is wasteful. Horner's rule factors the polynomial instead:
H = (...((c0·b + c1)·b + c2)·b + ... ) + c(m-1)
Each step multiplies the running value by b and adds the next code. Reducing mod p at every step keeps the intermediate values below p·b.
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
print(poly_hash("abc")) # (97*256^2 + 98*256 + 99) % modRunning this prints 6382179. That value is still below 1_000_000_007, so the modulus has no effect yet. On longer strings it will.
Common mistakes
- Reversed weights. Giving the last character the highest power is also a valid hash, but it breaks the rolling formula used in the next chapter. Pick one convention and keep it.
- Base smaller than the alphabet. With
b = 26and rawordvalues (97 to 122), digits overlap before any reduction. Use a base larger than the largest character code, or map characters to1..26. - Mapping a character to 0. If
'a'maps to 0, then"a","aa", and"aaa"all hash to 0. Start the mapping at 1. - Comparing hashes of different lengths. The hash does not encode length. Only compare hashes of equal-length strings.
Exercise
Using polyhash with base 256 and modulus 1000000007, what is the hash of "cab"? Show the Horner steps.
Show answer
h = 99; then 99256 + 97 = 25441; then 25441256 + 98 = 6512896 + 98 = 6512994. The value is below the modulus, so the hash is 6512994.
Exercise
With characters mapped as a=0, b=1, ..., z=25 and base 31, why do "b" and "ab" get the same hash, and how do you fix it?
Show answer
"ab" = 0*31 + 1 = 1, and "b" = 1, because a leading zero digit adds nothing. Map characters to 1..26 (for example ord(ch) - ord('a') + 1) so that no character contributes zero.