Sub topic 4
Sliding the Window: The Rolling Hash Update
This chapter assumes you can compute a polynomial hash with Horner's rule, as in the previous chapter. It also assumes you are comfortable with the modulo operator and the rules for reducing sums and products modulo a prime. The goal is one formula. Given the hash of a window of length m, it produces the hash of the next window in constant time, however large m is.
Why Recomputing Each Window Is Too Slow
A text of length n has n - m + 1 windows of length m. Hashing each window from scratch with Horner's rule takes m steps, so hashing all of them costs O((n - m + 1) · m). That is the same O(nm) bound as naive matching. Hashing only helps if consecutive windows can share work.
They overlap almost completely. Window i covers text[i .. i+m-1] and window i+1 covers text[i+1 .. i+m]. The two windows differ by one character leaving on the left and one character entering on the right. The rolling update turns that observation into arithmetic.
Deriving the Update
Write c_j for the numeric code of text[j], b for the base, and p for the modulus. Using the convention from the previous chapter, where the leftmost character gets the highest power, the hash of window i is:
H(i) = c_i·b^(m-1) + c_(i+1)·b^(m-2) + ... + c_(i+m-1)·b^0 (mod p)The next window is:
H(i+1) = c_(i+1)·b^(m-1) + c_(i+2)·b^(m-2) + ... + c_(i+m)·b^0 (mod p)Turning H(i) into H(i+1) takes three moves.
- Remove the outgoing character. Subtract
c_i·b^(m-1). What remains isc_(i+1)·b^(m-2) + ... + c_(i+m-1)·b^0. - Shift every remaining term up one power. Multiply by
b. This givesc_(i+1)·b^(m-1) + ... + c_(i+m-1)·b^1, and theb^0slot is now empty. - Add the incoming character. Add
c_(i+m), which fills theb^0slot.
Combined:
H(i+1) = ( (H(i) - c_i · b^(m-1)) · b + c_(i+m) ) mod pThe constant b^(m-1) mod p depends only on m, so you compute it once before the scan. Call it high, because it is the weight of the highest-order character. Each step then costs one subtraction, two multiplications, one addition, and one reduction. That is O(1) regardless of m.
Every step is valid modulo p because modular arithmetic preserves addition, subtraction, and multiplication. You can reduce intermediate values whenever you like and still get the same final remainder.
A Worked Example by Hand
Small numbers make the arithmetic visible. Treat the text 31415 as digits, use base b = 10 and modulus p = 13, and take window length m = 3. Then high = 10^2 mod 13 = 100 mod 13 = 9.
| Window | Direct hash | Rolling computation | Result |
|---|---|---|---|
| `314` | 314 mod 13 = 2 | (initial window, Horner) | 2 |
| `141` | 141 mod 13 = 11 | ((2 − 3·9)·10 + 1) mod 13 = (−249) mod 13 | 11 |
| `415` | 415 mod 13 = 12 | ((11 − 1·9)·10 + 5) mod 13 = 25 mod 13 | 12 |
Both columns agree. The second row passes through a negative intermediate value, −249. Its remainder modulo 13 is 11, because −249 = 13·(−20) + 11. Python's % returns that non-negative remainder automatically. C, C++, and Java do not, and a later chapter covers how to handle it in those languages.
Implementing the Update in Python
The function below yields the hash of every window. The test checks each rolled hash against a fresh Horner computation, which is the quickest way to catch an off-by-one or a wrong power.
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 rolling_hashes(text, m, base=256, mod=1_000_000_007):
"""Yield (i, hash of text[i:i+m]) for every window of length m."""
n = len(text)
if m <= 0 or m > n:
return
high = pow(base, m - 1, mod) # b^(m-1) mod p, computed once
h = poly_hash(text[:m], base, mod) # first window: O(m)
yield 0, h
for i in range(n - m): # each later window: O(1)
outgoing = ord(text[i])
incoming = ord(text[i + m])
h = ((h - outgoing * high) * base + incoming) % mod
yield i + 1, h
text = "the quick brown fox jumps over the lazy dog"
m = 5
for i, h in rolling_hashes(text, m):
assert h == poly_hash(text[i:i + m]), (i, text[i:i + m])
print("all", len(text) - m + 1, "rolled hashes match direct hashes")Running it prints all 39 rolled hashes match direct hashes. The windows "the q" at index 0 and "the l" at index 31 share a prefix but get different hashes. The equal 3-character windows "the" at index 0 and index 31 would get equal hashes if you ran the code with m = 3. That property is what the next chapter relies on.
Why `pow(base, m - 1, mod)` and Not `base ** (m - 1)`
The three-argument pow reduces modulo mod at each squaring step. It runs in O(log m) time and keeps every intermediate value small. Writing base ** (m - 1) % mod gives the same answer, but it first builds an integer with about 8·(m − 1) bits when base = 256. For a pattern of length 100,000 that is a 100 KB number, created only to be reduced.
Order of Operations Matters
The formula subtracts first and multiplies second. Reversing them is a common mistake. If you multiply H(i) by b first, the outgoing character's weight becomes b^m, so you must subtract c_i·b^m instead. The equivalent form is:
H(i+1) = ( H(i) · b - c_i · b^m + c_(i+m) ) mod pThis form is also correct if you precompute b^m instead of b^(m-1). The bug comes from mixing the two forms: multiplying first and then subtracting with high = b^(m-1). That produces hashes that look plausible and are wrong. Choose one form and keep its constant consistent with it.
Why the Convention Points Left to Right
You could define the hash the other way round, with the leftmost character at b^0 and the rightmost at b^(m-1). Under that convention, sliding the window lowers every power by one. To lower a power you divide by b, and modulo p that means multiplying by the modular inverse of b. The approach works because p is prime and b is not a multiple of p, but it adds an inverse computation and an extra multiplication. It also makes mistakes more likely. The left-to-right convention matches Horner's rule, needs only multiplication, and is the form used in the rest of this tutorial.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Rolled hashes diverge from direct hashes after the first step | `high` computed as `b^m` while subtracting before multiplying | Use `b^(m-1)` with subtract-then-multiply |
| Last window missing or index error | Loop runs `n - m + 1` times and reads `text[i + m]` on the final pass | Roll only `n - m` times, or guard with `if i < n - m` |
| Scan slows down as patterns get longer | Modulus omitted in the update, or `high` built without modular `pow` | Reduce every step and use `pow(b, m-1, p)` |
| Negative hashes (Java/C++) | `%` keeps the sign of the dividend | Add `p` before the final reduction (covered in a later chapter) |
| Crash or nonsense when `m > n` or `m == 0` | No windows exist, or `high` uses `b^(-1)` | Handle these cases before computing `high` |
Edge Cases Worth Testing
m == n: there is one window. The loop body never runs, which is correct.m == 1:high = b^0 = 1, and the update reduces toh = incoming % mod. The formula still holds, which makes this a good sanity check.- Repeated characters: in a text such as
"aaaaaaa", every window must have the same hash. A mismatch means the outgoing term is wrong. - Non-ASCII text:
ordcan return values above 255. That is harmless for correctness modulop. If you want each character's code to stay below the base, choose a base larger than your alphabet, as discussed in the chapter on choosing parameters.
Exercise
Using base 10, modulus 13, and window length 3 on the digit string "92653", compute the hash of the first window directly, then roll it twice. Verify each rolled value against a direct computation.
Show answer
high = 10^2 mod 13 = 9. H("926") = 926 mod 13 = 3 (13·71 = 923). Rolling: ((3 − 9·9)·10 + 5) mod 13 = (−775) mod 13 = 5, and 265 mod 13 = 5 (13·20 = 260). Rolling again: ((5 − 2·9)·10 + 3) mod 13 = (−127) mod 13 = 3, and 653 mod 13 = 3 (13·50 = 650). Both rolled values match.
Exercise
A colleague writes the update as h = (h base - ord(text[i]) high + ord(text[i + m])) % mod with high = pow(base, m - 1, mod). Will the hashes be correct? If not, what single change fixes it?
Show answer
No. Multiplying first raises the outgoing character's weight to b^m, but the code subtracts only c_i·b^(m-1). Fix it by setting high = pow(base, m, mod). Alternatively, keep high as b^(m-1) and subtract before multiplying: h = ((h - ord(text[i]) high) base + ord(text[i + m])) % mod.
Exercise
Modify rolling_hashes so it also works when the window slides right to left, from the end of the text toward the start, without changing the hash definition. What is the update from H(i+1) to H(i)?
Show answer
Going left, the character c(i+m) leaves from the b^0 slot and ci enters at the b^(m-1) slot. Subtract c(i+m), multiply by the modular inverse of b, then add ci·b^(m-1): H(i) = ((H(i+1) − c(i+m)) · invb + ci · high) mod p, where invb = pow(base, mod - 2, mod) because mod is prime. This is the division-based form that the left-to-right scan avoids.