Sub topic 7
Running Time: Expected O(n + m), Worst Case O(nm)
This chapter assumes you know Big-O notation and have read the earlier chapters, which covered the polynomial hash, the rolling update, and the full rabin_karp function that confirms every hash match with a direct comparison. Throughout, n is the text length, m is the pattern length, and p is the prime modulus.
Rabin-Karp is often described as a linear-time algorithm. That holds on average, but the worst case is still O(nm), the same bound as naive search. This chapter works out the exact cost, explains why the two bounds differ, and shows how to decide which one applies to your inputs.
Where the Time Goes
Split one run of Rabin-Karp into three phases and count the work in each.
| Phase | Work | Cost |
|---|---|---|
| Setup | Hash the pattern, hash the first window, compute `base^(m-1) mod p` | O(m) |
| Sliding | Roll the hash once for each of the `n - m + 1` windows and compare two integers | O(n) |
| Verification | Compare up to `m` characters each time the hashes are equal | O(m) per verification |
The first two phases always cost O(n + m), whatever the input. The third phase is the only variable part. Let v be the number of windows whose hash equals the pattern hash. Then:
T(n, m) = O(n + m) + O(m · v)
Each such window is one of two kinds:
- A true match: the window really equals the pattern. Call the count
occ. - A spurious hit: the hashes are equal but the strings differ, which is a collision. Call the count
s.
So v = occ + s, and the whole analysis comes down to how large occ and s can get.
Bounding the Spurious Hits
Suppose the base b is picked uniformly at random from [1, p - 1], and take two different strings x and y of length m. Their hash difference is a polynomial in b:
H(x) − H(y) = Σ (xi − yi) · b^(m−1−i) mod p
This polynomial has degree at most m − 1 and is not the zero polynomial, because x ≠ y and every character code is smaller than p. Over the field of integers mod a prime, a nonzero polynomial of degree d has at most d roots. At most m − 1 choices of b make the two hashes collide, so:
Pr[collision] ≤ (m − 1) / p
There are at most n − m + 1 windows, so linearity of expectation gives:
E[s] ≤ (n − m + 1) · (m − 1) / p
Each spurious hit costs at most m character comparisons, so the expected verification cost from collisions is at most about n · m² / p.
Try realistic numbers: n = 10^6, m = 10^3, p ≈ 10^9. That gives 10^6 · 10^6 / 10^9 = 1000 extra character comparisons, which is nothing next to the 10^6 rolling steps. With a fixed base and ordinary, non-adversarial text, the usual rule of thumb is a collision chance of about 1/p per window, which is smaller still.
The Expected Bound
With the spurious term under control, the expected running time is:
E[T] = O(n + m + m · occ + n·m²/p)
If p is much larger than n · m, the last term is O(m) or less. When the pattern occurs only a few times, which is the common case, m · occ is small too, and the expected time is O(n + m).
The Worst Case: True Matches Cost Too
Collisions are not the cause of the worst case. True matches are. Every true match must be verified, and verification reads all m characters.
Take the text "a" * n and the pattern "a" * m. Every window is a real occurrence, so occ = n − m + 1, and each verification does exactly m comparisons:
T = Θ((n − m + 1) · m) = Θ(nm) when m ≤ n/2
No choice of hash parameters helps. A perfect hash with zero collisions still pays Θ(nm) here. A worse but less likely case is an unlucky or attacked hash function that produces Θ(n) spurious hits, which also costs Θ(nm).
Measuring It
The function below is Rabin-Karp with the verification written as an explicit loop, so that it can count character comparisons and sort hash matches into true matches and spurious hits. It assumes 1 <= m <= n.
import random
def rabin_karp_count(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
matches = spurious = char_compares = 0
for i in range(n - m + 1):
if p_hash == t_hash:
k = 0
while k < m and text[i + k] == pattern[k]:
k += 1
char_compares += min(k + 1, m)
if k == m:
matches += 1
else:
spurious += 1
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return matches, spurious, char_compares
random.seed(1)
n, m = 10_000, 500
rand_text = "".join(random.choice("ab") for _ in range(n))
rand_pat = rand_text[2000:2000 + m]
print("random text, big prime:", rabin_karp_count(rand_text, rand_pat))
print("random text, mod=101: ", rabin_karp_count(rand_text, rand_pat, mod=101))
print("all 'a', big prime: ", rabin_karp_count("a" * n, "a" * m))Expected results:
- Random text, big prime: one true match (the occurrence planted at index 2000), almost certainly no spurious hits, and about 500 character comparisons. The 9,501 rolling steps dominate the cost.
- Random text,
mod=101: about9501 / 101 ≈ 94spurious hits. On a two-letter random alphabet each one fails after about two comparisons, so the cost stays low, but the counter shows the collisions. - All
'a': exactly(9501, 0, 4750500). That is 9,501 true matches times 500 comparisons each, the Θ(nm) case. It also takes noticeably longer to run.
Las Vegas or Monte Carlo
You can choose what to do when hashes match. The choice trades a guarantee on correctness against a guarantee on time.
| Variant | On hash match | Correctness | Running time |
|---|---|---|---|
| Las Vegas (verify) | Compare characters | Always correct | Expected O(n + m) without many matches; worst case O(nm) |
| Monte Carlo (trust hash) | Report without comparing | Wrong with probability ≤ (n − m + 1)(m − 1)/p | Worst case O(n + m) |
| Monte Carlo + double hash | Report if both hashes agree | Error chance roughly squared | Worst case O(n + m), with a larger constant |
The Monte Carlo variant removes the m · v term completely, so all-'a' input runs in linear time. With p ≈ 10^9 and the numbers used earlier, the bound on the error probability is about 10^6 · 10^3 / 10^9 = 1, which guarantees nothing. To trust the hash alone you need a much larger modulus, a 61-bit prime or two hashes combined. A later chapter covers double hashing.
Reporting Occurrences Versus Counting Work
Output size is sometimes confused with running time. All-'a' input has n − m + 1 occurrences, so any algorithm that lists them writes Θ(n) values. KMP and the Z-algorithm find all of them in O(n + m) in the worst case, deterministically. Rabin-Karp with verification spends Θ(nm) because it re-checks overlapping characters it has already seen. The cost comes from the verification strategy. Listing the matches does not force it.
Decision Criteria
- One pattern, text you trust, few expected matches: Rabin-Karp with verification. It is simple and runs in expected linear time.
- Highly repetitive text or a hard worst-case requirement: KMP or the Z-algorithm, which guarantee O(n + m).
- You need hashes for other work (comparing substrings, many patterns, binary search over lengths): rolling hashes, with Monte Carlo checks and a large or doubled modulus, or with verification if exact answers matter and matches are rare.
- Input supplied by an adversary: randomize the base, as the later parameter chapter explains, or the expected bound does not apply.
Exercise
Text length n = 2,000,000, pattern length m = 2,000, modulus p = 1,000,000,007, random base. The pattern occurs 3 times. Estimate the expected number of character comparisons spent on verification, using the (m − 1)/p collision bound.
Show answer
True matches cost 3 · 2000 = 6000 comparisons. Expected spurious hits are at most (2,000,000 − 2000 + 1) · 1999 / 1,000,000,007 ≈ 4.0, each costing at most 2000 comparisons, so about 8000 more. The total is roughly 14,000 comparisons, small next to the roughly 2,000,000 rolling steps. The run is effectively O(n + m).
Exercise
Make a text of length n and a pattern of length m that force Θ(nm) verification work even with a perfect hash that never collides. Does switching the modulus from 10^9+7 to a 61-bit prime help?
Show answer
Use text "a" n and pattern "a" m, or any periodic text that contains the pattern at almost every position. Every window is a true match, so each of the n − m + 1 windows costs m comparisons. A larger modulus only lowers the number of spurious hits, and there are none here, so it does not help. Only skipping verification (Monte Carlo) or switching to KMP or the Z-algorithm removes the Θ(nm) cost.
Exercise
In rabinkarpcount, the verification loop exits at the first mismatch. Why does random text with mod=101 stay cheap even with about 94 spurious hits, and what kind of text would make those spurious hits expensive?
Show answer
On random text a spurious window usually differs from the pattern within the first few characters, so each failed check costs O(1) comparisons on average. Spurious hits become expensive when the colliding windows share a long prefix with the pattern, for example a text built from near-copies of the pattern that differ only in the last character. Then each failed check costs close to m comparisons, and the collision cost approaches s · m.