Sub topic 5
Putting It Together: The Rabin-Karp Algorithm
This chapter assumes you already know three things from earlier chapters: the polynomial hash of a string, how to reduce it modulo a prime, and the constant-time rolling update that moves the window hash one character to the right. Here those pieces become one working search function.
The Idea in One Paragraph
Rabin-Karp finds every position where a pattern of length m occurs in a text of length n. It hashes the pattern once. It then slides a window of length m across the text and keeps that window's hash up to date with the rolling update. When the two hashes are equal, the window might be a match, so the algorithm compares the actual characters before reporting it. When the hashes differ, the window cannot be a match, and the algorithm skips it without comparing a single character.
The Implementation
def rabin_karp(text, pattern, base=256, mod=1_000_000_007):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
high = pow(base, m - 1, mod) # weight of the leading character
p_hash = t_hash = 0
for i in range(m):
p_hash = (p_hash * base + ord(pattern[i])) % mod
t_hash = (t_hash * base + ord(text[i])) % mod
matches = []
for i in range(n - m + 1):
if p_hash == t_hash and text[i:i + m] == pattern:
matches.append(i)
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return matches
print(rabin_karp("abracadabra", "abra")) # [0, 7]Walking Through the Code
| Step | Line(s) | Purpose |
|---|---|---|
| Edge cases | `m == 0`, `m > n` | An empty pattern matches at every index from 0 to `n`. A pattern longer than the text matches nowhere. |
| Leading weight | `high = pow(base, m - 1, mod)` | Precomputes the factor of the outgoing character, so each roll costs O(1). |
| Initial hashes | first `for` loop | Builds the pattern hash and the first window hash together with Horner's rule. |
| Check | `p_hash == t_hash and ...` | The hash comparison is a cheap filter. The slice comparison confirms the match. |
| Roll | `if i < n - m` | Moves to the next window. The guard stops the code from reading `text[n]` after the last window. |
Python's % always returns a non-negative result for a positive modulus, so the subtraction inside the roll needs no special handling. Fixed-width languages handle this differently, as a later chapter shows.
Common Mistakes
- Rolling after the last window. If you drop the
i < n - mguard, you get anIndexErroron the final iteration. - Using `base (m - 1)
without a modulus.** The result is correct, but the integers grow huge and each roll gets slower.pow(base, m - 1, mod)` keeps the value small. - Mismatched parameters. The pattern and the text windows must use the same
baseandmod, or the hashes can never be compared. - Hashing each window from scratch. That costs O(m) per window and throws away the whole benefit of the rolling update.
Exercise
What does rabin_karp("aaaa", "aa") return, and how many times does the slice comparison run?
Show answer
It returns [0, 1, 2]. Every window "aa" has the same hash as the pattern, so the slice comparison runs at all 3 windows, and every comparison succeeds.
Exercise
Change the function so it returns only the first match index, or -1 if there is none. Which line changes?
Show answer
Replace matches.append(i) with return i, and replace the final return matches with return -1. The m == 0 case should then return 0, and the m > n case should return -1.