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, and that you know how % behaves in Python. The goal is to get the hash of the next window from the current one in O(1) time. Recomputing it from scratch would take O(m).
The Idea with Decimal Digits
Treat the string "1234" as digits in base 10. Take windows of length m = 3. The first window is the number 123. To get the next window, 234, you:
- Remove the leading digit's contribution: 123 − 1·10² = 23.
- Shift everything left one place: 23 · 10 = 230.
- Add the new digit: 230 + 4 = 234.
A polynomial hash works the same way. The base B plays the role of 10, and character codes play the role of digits.
Deriving the Update
For a window starting at index i with length m, the hash is:
H(i) = (s[i]·B^(m−1) + s[i+1]·B^(m−2) + … + s[i+m−1]·B⁰) mod M
The leading character carries weight B^(m−1). To move to window i+1, subtract that term, multiply by B so each remaining character moves up one power, and add the incoming character at weight B⁰:
H(i+1) = ((H(i) − s[i]·B^(m−1))·B + s[i+m]) mod M
Every operation here is addition, subtraction, or multiplication, so you can reduce mod M at any point and the result stays correct. This is the property from the modular arithmetic chapter. The factor B^(m−1) mod M depends only on m, so compute it once before the loop.
Implementation and a Self-Check
The code below rolls across every window and checks each result against a full recomputation.
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 roll(h, outgoing, incoming, high, base=256, mod=1_000_000_007):
return ((h - ord(outgoing) * high) * base + ord(incoming)) % mod
text, m = "abracadabra", 4
mod = 1_000_000_007
high = pow(256, m - 1, mod) # weight of the leading character
h = poly_hash(text[:m])
for i in range(len(text) - m):
h = roll(h, text[i], text[i + m], high)
assert h == poly_hash(text[i + 1:i + m + 1])
print("all windows match")Python integers never overflow, and Python's % always returns a non-negative result when the modulus is positive. That is why the subtraction is safe here without any extra steps.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using B^m instead of B^(m−1) | Hashes drift after the first roll | The leading character's weight is B^(m−1) |
| Calling `pow` inside the loop | Each step takes O(log m) time | Compute `high` once, before the loop |
| Adding the new character before multiplying | Wrong hash | Multiply by B first, then add |
| Rolling one step past the last window | Index error on `text[i + m]` | Roll only while i < n − m |
| Porting to Java or C++ as written | Negative results or overflow | Add M before reducing; covered in a later chapter |
Exercise
With base B = 10 and no modulus, the window "472" has hash 472. The next character is "9". Compute the next window's hash using the rolling formula, showing each step.
Show answer
high = 10² = 100. Subtract: 472 − 4·100 = 72. Multiply: 72·10 = 720. Add: 720 + 9 = 729. This matches the window "729".
Exercise
Why does the rolling update give the same result whether you reduce mod M after every operation or only at the end?
Show answer
The update uses only addition, subtraction, and multiplication. Reduction mod M is compatible with all three, so reducing early changes the size of the intermediate values but not the final remainder.