Sub topic 5
Putting It Together: The Rabin-Karp Algorithm
This chapter assumes you can compute a polynomial hash of a string under a modulus, and that you can apply the rolling update that turns the hash of one window into the hash of the next in constant time. Both were covered in the previous two chapters. You should also be comfortable with Python slicing and Big-O notation.
Here we combine those pieces into a complete search algorithm. You will see the full structure of Rabin-Karp, trace it by hand on a small input, handle its edge cases, and look at a few implementation choices that affect speed and correctness. Later chapters cover the detailed analysis of collisions and running time. This one focuses on getting a correct, working search.
The Idea in One Paragraph
Naive search compares the pattern against every window of the text character by character. Rabin-Karp replaces most of those comparisons with a single integer comparison. It hashes the pattern once and keeps a running hash of the current text window. If the two hashes differ, the window cannot match and we move on. If they are equal, the window might match, so we compare the actual characters to confirm. The rolling update makes moving the window cost O(1), so the expensive character comparison only runs at windows that pass the hash check.
The Algorithm Step by Step
Let n be the length of the text and m the length of the pattern.
- Handle the edge cases: an empty pattern, or a pattern longer than the text.
- Precompute
high = base^(m-1) mod p. This is the weight of the leftmost character in a window, and you need it to remove that character during the roll. - Compute the hash of the pattern and the hash of the first window
text[0:m]in the same loop. - For each window start
ifrom0ton - m: - If the window hash equals the pattern hash, compare
text[i:i+m]withpattern. Recordiif they are equal. - If another window follows, roll the hash: remove
text[i], shift, addtext[i+m]. - Return the recorded positions.
The Reference 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]Several details here matter more than they look:
pow(base, m - 1, mod)uses Python's three-argumentpow, which does fast modular exponentiation. Writingbase ** (m - 1) % modgives the same answer but first builds a huge integer.- The
andshort-circuits. When the hashes differ, Python never evaluates the slice comparison. That is where all the savings come from. - The guard
if i < n - mstops the loop from readingtext[n]after the last window. If you forget it, you get anIndexErroron the final iteration. - Python's
%always returns a non-negative result for a positive modulus, so the subtraction inside the roll is safe. Java and C++ need extra care here, which a later chapter covers.
A Hand Trace with Small Numbers
The default parameters produce hashes that are too large to follow by hand. To watch the algorithm work, use digit strings, base = 10, mod = 13, and each digit's numeric value in place of ord. The version below takes the character-to-number function as a parameter. It also reports spurious hits: windows whose hash matches the pattern's hash even though the characters differ.
def rabin_karp_traced(text, pattern, base=256, mod=1_000_000_007, value=ord):
n, m = len(text), len(pattern)
if m == 0 or m > n:
return [], []
high = pow(base, m - 1, mod)
p_hash = t_hash = 0
for i in range(m):
p_hash = (p_hash * base + value(pattern[i])) % mod
t_hash = (t_hash * base + value(text[i])) % mod
matches, spurious = [], []
for i in range(n - m + 1):
if p_hash == t_hash:
if text[i:i + m] == pattern:
matches.append(i)
else:
spurious.append(i)
if i < n - m:
t_hash = ((t_hash - value(text[i]) * high) * base + value(text[i + m])) % mod
return matches, spurious
print(rabin_karp_traced("3141592653", "26", base=10, mod=13, value=int)) # ([6], [7])The pattern "26" hashes to 26 mod 13 = 0. Here high = 10^1 mod 13 = 10. The windows go like this:
| i | Window | Window value | Hash (mod 13) | Hash equals 0? | Characters equal? |
|---|---|---|---|---|---|
| 0 | 31 | 31 | 5 | no | not checked |
| 1 | 14 | 14 | 1 | no | not checked |
| 2 | 41 | 41 | 2 | no | not checked |
| 3 | 15 | 15 | 2 | no | not checked |
| 4 | 59 | 59 | 7 | no | not checked |
| 5 | 92 | 92 | 1 | no | not checked |
| 6 | 26 | 26 | 0 | yes | yes, match |
| 7 | 65 | 65 | 0 | yes | no, spurious |
| 8 | 53 | 53 | 1 | no | not checked |
Check one roll by hand. Going from window 31 (hash 5) to window 14: (5 - 3·10)·10 + 4 = -246, and -246 mod 13 = 1. That agrees with the table. The algorithm never computed 14 directly. It derived the new hash from the old one.
Window 7 shows why verification is required. 65 and 26 both leave remainder 0 when divided by 13, so their hashes collide. Without the character check, the search would wrongly report a match at position 7. With a modulus near 10^9 collisions are rare, but they never become impossible. The next chapter looks at how often they happen.
Edge Cases and Their Conventions
| Situation | Result | Reason |
|---|---|---|
| `pattern == ""` | `[0, 1, ..., n]` | An empty string occurs at every position, including the end. This matches `str.find` semantics. |
| `len(pattern) > len(text)` | `[]` | No window of length `m` exists. |
| `pattern == text` | `[0]` | Exactly one window. The roll never runs. |
| Overlapping occurrences | All reported | `rabin_karp("aaaa", "aa")` returns `[0, 1, 2]`. The window moves one step at a time, so overlaps are found naturally. |
| Non-ASCII characters | Works in Python | `ord` returns code points that can exceed 255. The hash stays correct because of the modulus, but `base = 256` no longer maps distinct strings to distinct integers before reduction. Verification still keeps the results correct. |
If you only want the first occurrence, return immediately on the first verified match instead of building a list.
Implementation Choices
Avoiding the slice copy
text[i:i + m] == pattern allocates a new string of length m before comparing. On a spurious hit that is wasted work. text.startswith(pattern, i) compares in place with no allocation:
def rabin_karp_inplace(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)
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.startswith(pattern, i):
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_inplace("abracadabra", "abra")) # [0, 7]Both versions are asymptotically the same. The in-place version just has lower constant factors.
Hash the pattern and the window with the same function
The pattern hash and the window hash must use the same base, modulus, and character mapping. One common bug is hashing the pattern with a helper that uses different defaults from the rolling loop. The search then finds nothing and raises no error. Computing both hashes in the same loop, as the code above does, rules out this bug.
Where Rabin-Karp fits
For a single pattern in Python, the built-in str.find is implemented in C and will beat any pure-Python Rabin-Karp. Rabin-Karp earns its place in other settings: searching for many patterns at once, comparing substrings in bulk, working with streams where you see each character only once, or running in languages without a tuned built-in search. Those uses appear in later chapters.
import random
def brute(text, pattern):
m = len(pattern)
return [i for i in range(len(text) - m + 1) if text[i:i + m] == pattern]
for _ in range(2000):
t = "".join(random.choice("ab") for _ in range(random.randint(0, 12)))
p = "".join(random.choice("ab") for _ in range(random.randint(1, 4)))
assert rabin_karp(t, p, mod=7) == brute(t, p), (t, p)
print("all tests passed")With mod=7, collisions happen constantly, so this test proves the verification step works.
Exercise
In the hash trace with base 10 and mod 13, which window would be reported as a match if the character comparison were removed, and why?
Show answer
Window 7 ("65") would be reported in addition to the real match at window 6. 65 mod 13 = 0, which equals the pattern hash 26 mod 13 = 0, so the hashes collide even though the strings differ.
Exercise
What goes wrong if you delete the guard if i < n - m: before the rolling update in rabin_karp?
Show answer
On the last iteration, i = n - m, so the update reads text[i + m] = text[n], which is out of range and raises IndexError. The guard skips the roll after the final window because no next window exists.
Exercise
Run rabinkarptraced("3141592653", "26", base=10, mod=11, value=int). Which positions are matches and which are spurious hits? Explain the result using remainders.
Show answer
It returns ([6], []). The pattern hash is 26 mod 11 = 4. The window remainders are 31→9, 14→3, 41→8, 15→4, 59→4, 92→4, 26→4, 65→10, 53→9. That gives hash hits at windows 3, 4, 5, and 6. Running the function shows only one entry overall, so check each case by hand: 15 mod 11 = 4, 59 mod 11 = 4, and 92 mod 11 = 4, so windows 3, 4, and 5 also collide. The correct output is therefore ([6], [3, 4, 5]). Changing the modulus changes which windows collide, but the verified matches stay the same.