Sub topic 3
Hashing a String as a Polynomial
This chapter assumes you can write loops in Python, know what % does on non-negative integers, and have read the previous chapter on modular arithmetic. In particular, it relies on the fact that you can reduce modulo mod after every addition and multiplication without changing the final remainder. Here you will turn a string into a single integer in a way that respects character order, compute it efficiently with Horner's rule, and learn the mistakes that quietly break string hashes.
Why a Hash Needs to Encode Order
A string hash maps a string to an integer. Rabin-Karp compares these integers instead of comparing characters, so two different strings should rarely get the same value.
The simplest idea is to add up the character codes. It fails quickly:
| String | Sum of `ord` values |
|---|---|
| `"abc"` | 97 + 98 + 99 = 294 |
| `"cba"` | 99 + 98 + 97 = 294 |
| `"bac"` | 98 + 97 + 99 = 294 |
Every permutation of the same letters collides. Text is full of anagrams and repeated letters, so a sum hash would report a false match at almost every window. The hash has to give each position its own weight.
The Polynomial Definition
Treat the string as the digits of a number written in base B. For a string s of length m, with c_i = ord(s[i]):
H(s) = c0 · B^(m-1) + c1 · B^(m-2) + ... + c(m-2) · B + c(m-1) (mod M)
The first character gets the highest power and the last character gets power 0. This is the same as reading a decimal number: in 472, the 4 is worth 4 · 10².
If you choose B larger than every character code, then before any reduction modulo M the map from strings of a fixed length to integers is one-to-one. Each string is literally a distinct base-B number. With bytes (codes 0 to 255) and B = 256, the unreduced value of "abc" is the three-byte integer 0x616263. Taking the result modulo M is what introduces collisions, because infinitely many integers share each remainder. The chapter on collisions deals with that cost.
Computing It with Horner's Rule
Evaluating each power separately costs extra multiplications and produces large intermediate numbers. Horner's rule rewrites the polynomial as nested multiplications:
H = (((c0 · B + c1) · B + c2) · B + ... ) · B + c(m-1)
Each step multiplies the running value by B and adds the next character. Reducing modulo M at every step keeps the running value below M, which is allowed by the modular arithmetic rules from the previous chapter.
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) % modThis makes one multiplication, one addition, and one reduction per character, so hashing a string of length m takes O(m) time and O(1) extra space.
A Worked Trace
Here is poly_hash("abc") with B = 256 and M = 1_000_000_007:
| Step | Character | Code | Computation | `h` after step |
|---|---|---|---|---|
| start | 0 | |||
| 1 | `a` | 97 | 0 · 256 + 97 | 97 |
| 2 | `b` | 98 | 97 · 256 + 98 | 24,930 |
| 3 | `c` | 99 | 24,930 · 256 + 99 | 6,382,179 |
The result 6,382,179 is below M, so no reduction happened. Expanding the definition directly gives the same value: 97 · 65,536 + 98 · 256 + 99 = 6,356,992 + 25,088 + 99 = 6,382,179. The reversed string "cba" hashes to 99 · 65,536 + 98 · 256 + 97 = 6,513,249, so the permutation that broke the sum hash now gets a different value.
Checking Horner Against the Definition
The script below compares Horner's rule against a direct evaluation of the formula. Python integers have no size limit, so the direct version can compute the exact value before reducing it once at the end. That makes it a useful reference to test against.
import random
import string
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
def poly_hash_direct(s, base=256, mod=1_000_000_007):
m = len(s)
exact = sum(ord(ch) * base ** (m - 1 - i) for i, ch in enumerate(s))
return exact % mod
random.seed(1)
for _ in range(1000):
s = "".join(random.choices(string.ascii_letters, k=random.randint(0, 40)))
assert poly_hash(s) == poly_hash_direct(s)
print(poly_hash("abc"), poly_hash("cba")) # 6382179 6513249
print("Horner matches the definition on 1000 random strings")Why Reduce at Every Step
You could skip % mod inside the loop in Python and reduce once at the end. You get the same answer, but the cost is different. The unreduced hash of a string of length m has about 8m bits, so each multiplication works on a larger and larger number and hashing the string becomes roughly quadratic. In Java or C++, the unreduced value overflows a 64-bit integer after about eight characters with B = 256. Reducing every step keeps h < M, so h * base + code stays below about 2.6 × 10¹¹, which fits in 64 bits. A later chapter covers the overflow details for fixed-width languages, including the subtraction in the rolling update.
Common Errors
Mapping a Character to Zero
People often map letters with ord(ch) - ord('a') so that a becomes 0. Then a leading a adds nothing to the hash:
| String | Codes with `a = 0` | Hash |
|---|---|---|
| `"b"` | 1 | 1 |
| `"ab"` | 0, 1 | 0 · B + 1 = 1 |
| `"aab"` | 0, 0, 1 | 1 |
For strings of the same length, which is the only comparison plain Rabin-Karp makes, the hash is still one-to-one before reduction. Once you compare substrings of different lengths, as in the prefix-hash and multi-pattern chapters, these strings collide every time. Map letters to 1 through 26 (ord(ch) - ord('a') + 1), or keep the raw ord values. The same problem affects raw bytes that contain \0: "\0a" and "a" hash identically under ord.
A Base Smaller Than the Alphabet
If B is not larger than the largest character code, different strings of the same length can collide even before reduction. With B = 2:
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("ab", base=2), poly_hash("b`", base=2)) # 292 292Here 97 · 2 + 98 = 292 and 98 · 2 + 96 = 292. The carry from one "digit" spills into the next. A small base does not always break the hash, because the modulus mixes values anyway. Still, there is no reason to throw away the collision-free structure, and a later chapter gives the full rules for choosing B and M.
Unicode Code Points Above the Base
ord returns Unicode code points, which go up to 1,114,111. With B = 256, a string such as "é中" has codes larger than the base, and the one-to-one property is lost. You can choose a base above 1,114,111, or hash the UTF-8 bytes with s.encode("utf-8") and iterate over the integers that gives you. If you hash bytes, the text and the pattern must use the same encoding. Byte offsets will also differ from character offsets.
Reusing a Hash Across Different Parameters
A hash value only means something together with its (B, M) pair and its ordering convention. Comparing a pattern hash computed with one base against window hashes computed with another produces no matches and raises no error. Store the parameters in one place, such as default arguments or module constants, and pass them through.
What This Sets Up
The highest-power-first form has one property that the next chapter depends on. The leading character's contribution is exactly c_0 · B^(m-1), so you can subtract it, multiply what remains by B, and add a new trailing character. That produces the hash of the next window in constant time, without running Horner's rule over the whole window again.
Exercise
Using base 10 and no modulus, with characters mapped as a=1, b=2, c=3, compute the polynomial hash of "cab" by Horner's rule, showing each intermediate value.
Show answer
Start at 0. After 'c': 0·10 + 3 = 3. After 'a': 3·10 + 1 = 31. After 'b': 31·10 + 2 = 312. The hash is 312, which matches 3·100 + 1·10 + 2.
Exercise
A colleague hashes lowercase words with ord(ch) - ord('a'), base 31, mod 1000000_007, and puts the hashes of words of mixed lengths in one set. Why does the set report that "at" and "t" are the same word, and what is the smallest fix?
Show answer
'a' maps to 0, so a leading 'a' adds 0 · 31 to the hash and "at" hashes to the same value as "t" (19). Map letters to 1 through 26 with ord(ch) - ord('a') + 1, or use raw ord values, so that no character contributes zero.
Exercise
Without a modulus and with base 256, explain why two different byte strings of the same length can never have the same polynomial hash, and say what changes once you reduce modulo M.
Show answer
Every byte is in 0 to 255, which is less than 256, so the hash is the string's base-256 representation and each value has exactly one digit sequence. Reducing modulo M maps infinitely many integers to M remainders, so distinct strings can share a remainder. Collisions become possible and matches must be verified.