Sub topic 7
Running Time: Expected O(n + m), Worst Case O(nm)
This chapter assumes you know Big-O notation, the Rabin-Karp loop from the previous chapter, and the idea that a hash match must be confirmed by direct comparison. Here we add up what each part of that loop costs.
Throughout, n is the text length, m is the pattern length, and k is the number of windows that get verified.
Where the Time Goes
Rabin-Karp's work falls into three parts:
- Setup. Computing the pattern hash, the first window hash, and
base^(m-1) mod ptakes O(m). - Sliding. There are
n - m + 1windows. Each rolling update and each hash comparison costs O(1), so sliding costs O(n) in total. - Verification. Each window whose hash equals the pattern hash triggers a character-by-character check that costs up to O(m).
That gives a total of O(n + m + k·m). The value of k decides everything.
Two Kinds of Verified Windows
A verification happens for one of two reasons:
- Real matches. The window really equals the pattern. A verification here is useful work.
- Spurious hits. The hashes collide but the strings differ. A verification here is wasted work.
Pick a prime modulus p and choose the base at random. Two different strings of length m collide only if the base is a root of a nonzero polynomial of degree at most m - 1. Such a polynomial has at most m - 1 roots modulo p, so the collision probability per window is at most (m - 1)/p. Over all windows, the expected number of spurious hits is at most about n·m/p. With p ≈ 10^9 and typical inputs, that is far below one.
So the expected cost is O(n + m + r·m), where r is the number of real matches. If you report only the first match, or if matches are rare, the cost is expected O(n + m).
The Worst Case
There are two ways to reach O(nm):
| Cause | Example | Can you avoid it? |
|---|---|---|
| Many real matches | text `"aaaa…a"`, pattern `"aaa…a"` | Not if you verify every match. Every window really matches. |
| Many collisions | Input built against a fixed, known base and modulus | Yes, by randomizing the parameters (covered in a later chapter) |
| Unlucky hashing by chance | Random parameters, ordinary input | Very unlikely, about `n·m/p` expected spurious hits |
The first row matters most in practice. Even a perfect hash cannot help there, because each verification confirms a real match.
Measuring It
This version counts character comparisons so you can see the two regimes:
import random
def rabin_karp_cost(text, pattern, base=256, mod=1_000_000_007):
n, m = len(text), len(pattern)
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
verifications = compares = matches = 0
for i in range(n - m + 1):
if p_hash == t_hash:
verifications += 1
j = 0
while j < m:
compares += 1
if text[i + j] != pattern[j]:
break
j += 1
if j == m:
matches += 1
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return verifications, compares, matches
random.seed(1)
random_text = "".join(random.choice("ab") for _ in range(10_000))
random_pat = "".join(random.choice("ab") for _ in range(20))
print(rabin_karp_cost(random_text, random_pat)) # few or no verifications
print(rabin_karp_cost("a" * 10_000, "a" * 20)) # (9981, 199620, 9981)In the second run, every one of the 9,981 windows is a real match, and each costs 20 comparisons. That adds up to (n - m + 1)·m work.
Exercise
A text has length 1,000,000, the pattern has length 1,000, and the pattern occurs exactly 3 times. You use a random base and the prime p = 1,000,000,007. Roughly how much work does Rabin-Karp do, and what is the expected number of spurious hits?
Show answer
Setup and sliding cost about n + m ≈ 1,001,000 steps. The 3 real matches add about 3 × 1,000 = 3,000 comparisons. Expected spurious hits are at most about n·m/p = 10^9 / (10^9 + 7), which is just under 1, adding at most about 1,000 more comparisons. The total is about 1 million steps, which is effectively O(n + m).
Exercise
Why can no choice of base or modulus bring Rabin-Karp below O(nm) when searching for "aa…a" (length m) in "aa…a" (length n) and reporting all matches with verification?
Show answer
Every window is a real match, so all n - m + 1 windows must be verified. Each verification compares m characters. That cost comes from real matches, not collisions, so a better hash does not reduce it.