Sub topic 12
Searching for Many Patterns of the Same Length
This chapter assumes you already know the single-pattern Rabin-Karp loop from earlier chapters: the polynomial hash, the rolling update, and the rule that every hash match must be confirmed by direct comparison. You should also be comfortable with Python dictionaries and sets, and with the expected-time argument for Rabin-Karp.
Here is the new problem. You have one text and a list of k patterns, and you want every position where any of them occurs. A spam filter checks a message against thousands of banned phrases. A plagiarism checker looks for any of a few thousand 8-word sequences from a source document. A DNA tool scans a genome for a set of known 20-base markers.
The cost of searching once per pattern
The obvious approach runs single-pattern Rabin-Karp k times. Each run costs expected O(n + m), so the total is O(k(n + m)). With a 10 MB text and 5,000 patterns, that means 5,000 passes over 10 million characters.
Notice what those passes have in common. When all patterns share the same length m, every pass computes exactly the same sequence of window hashes. Only the value each window is compared against changes. So you can compute the window hashes once and compare each one against all k pattern hashes at the same time.
A hash table makes that comparison O(1) on average. Store the pattern hashes in a dictionary, roll through the text once, and look up each window hash.
| Approach | Preprocessing | Scan | Total (expected) |
|---|---|---|---|
| Naive, each pattern separately | none | O(kmn) worst case | O(kmn) |
| Rabin-Karp run k times | O(km) | O(kn) | O(k(n + m)) |
| One pass with a hash table | O(km) | O(n) plus verification | O(n + km) plus verification |
Verification costs O(m) for each window whose hash matches. The section on running time below explains when that cost matters.
How the single pass works
The dictionary maps each hash value to a set of patterns. A set is needed because two different patterns can have the same hash. If you store a single pattern per hash, the second one overwrites the first, and its matches disappear without any error.
Implementation
This version validates its input. It accepts any iterable of patterns, removes duplicates, rejects mixed lengths with a clear error, and handles an empty pattern collection.
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 find_any(text, patterns, base=256, mod=1_000_000_007):
"""Return (index, pattern) for every occurrence of any pattern.
All patterns must have the same length. Results are sorted by index.
"""
patterns = set(patterns)
if not patterns:
return []
lengths = {len(p) for p in patterns}
if len(lengths) != 1:
raise ValueError("all patterns must have the same length")
m = lengths.pop()
n = len(text)
if m == 0 or m > n:
return []
wanted = {}
for pat in patterns:
wanted.setdefault(poly_hash(pat, base, mod), set()).add(pat)
high = pow(base, m - 1, mod)
t = poly_hash(text[:m], base, mod)
hits = []
for i in range(n - m + 1):
bucket = wanted.get(t)
if bucket is not None:
window = text[i:i + m]
if window in bucket:
hits.append((i, window))
if i < n - m:
t = ((t - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return hits
print(find_any("the cat sat on the mat", ["cat", "mat"]))
# [(4, 'cat'), (19, 'mat')]Look at the order of the checks. The slice text[i:i + m] is built only after the integer lookup wanted.get(t) succeeds. Building the slice and hashing it for set membership both cost O(m). If the code did that for every window, the scan would become O(nm) and you would lose the benefit of rolling.
At each position at most one pattern can match, because patterns of the same length that both equal the window must equal each other. So each position produces at most one hit.
Showing that verification keeps it correct
A good way to test hash-based code is to make collisions happen often on purpose. With mod=7 there are only seven possible hash values, so the table buckets fill with unrelated patterns and many windows match a hash without matching any pattern. If verification is right, the output still agrees exactly with brute force.
import random
def brute(text, patterns):
patterns = set(patterns)
if not patterns:
return []
m = len(next(iter(patterns)))
if m == 0:
return []
return [(i, text[i:i + m])
for i in range(len(text) - m + 1)
if text[i:i + m] in patterns]
random.seed(1)
for _ in range(500):
text = "".join(random.choice("ab") for _ in range(30))
pats = {"".join(random.choice("ab") for _ in range(3)) for _ in range(4)}
assert find_any(text, pats, mod=7) == brute(text, pats)
print("ok")Run this test with mod=7 and then with the default modulus. Both should print ok. The tiny modulus slows the search down but never changes the answer.
Running time and its edge cases
Preprocessing hashes k patterns of length m, which costs O(km). The scan does O(1) work per window for rolling and lookup, which costs O(n). Verification costs O(m) per window whose hash is in the table, and these windows come in two kinds.
True matches. Each real occurrence costs O(m) to confirm. If the text is "a" * n and a pattern is "a" * m, almost every window is a true match and the total is O(nm). This cost depends on the output size and cannot be avoided by any method that confirms matches. If you only need a yes or no answer, stop at the first verified hit.
False positives. For a random modulus near p, one window collides with one particular pattern hash with probability about 1/p. With k distinct pattern hashes in the table, the chance rises to about k/p per window. The expected number of false positives over the whole scan is about nk/p. With p ≈ 10⁹, n = 10⁷, and k = 10⁴, that gives roughly 100 false positives. Each costs O(m), so they add little time. With a 32-bit-sized modulus and larger k, though, nk/p climbs quickly. This is where a larger modulus or the double hashing from the earlier chapter is worth the cost: use a pair of hashes, or one combined integer, as the dictionary key.
The overall expected time is O(n + km + occ·m), where occ is the number of real occurrences.
| Edge case | Behavior of `find_any` |
|---|---|
| No patterns | Returns `[]` |
| Duplicate patterns in input | Removed by `set(patterns)` |
| Empty-string pattern | Returns `[]`; handle it separately if you need it |
| Patterns longer than text | Returns `[]` |
| Overlapping occurrences | All reported, e.g. `"aa"` in `"aaa"` at 0 and 1 |
| Mixed lengths | Raises `ValueError` |
Patterns of different lengths
The rolling window has a fixed width, so a single pass works for only one length. The usual fix is to group patterns by length and do one pass per distinct length.
def find_all_lengths(text, patterns):
by_len = {}
for p in set(patterns):
if p:
by_len.setdefault(len(p), set()).add(p)
hits = []
for group in by_len.values():
hits.extend(find_any(text, group))
hits.sort()
return hits
print(find_all_lengths("she sells sea shells", ["she", "sea", "sells", "shells"]))
# [(0, 'she'), (4, 'sells'), (10, 'sea'), (14, 'she'), (14, 'shells')]With L distinct lengths, this costs O(Ln + total pattern length) expected, plus verification. When L is small, as with fixed-size tokens, k-mers, or word n-grams, it works well. When patterns come in hundreds of different lengths, L passes become expensive. Then the Aho-Corasick automaton is usually the better choice: it handles any mix of lengths in one pass in O(n + total pattern length + occ) worst case, with no collisions. It costs more to implement and uses more memory per pattern character.
| Situation | Reasonable choice |
|---|---|
| Many patterns, one length | Rolling hash with a hash table |
| Many patterns, few distinct lengths | Group by length, one pass each |
| Many patterns, many lengths, worst-case guarantees needed | Aho-Corasick |
| Input chosen by an adversary | Randomized parameters or double hashing, or Aho-Corasick |
Exercise
A colleague stores pattern hashes as wanted = {poly_hash(p): p for p in patterns} and checks if t in wanted and text[i:i+m] == wanted[t]. Describe an input on which this gives a wrong answer, and say whether it can report a false match.
Show answer
It can never report a false match, because each hit is still compared character by character. It can miss matches. If two patterns p1 and p2 have the same hash, the dictionary comprehension keeps only the one inserted last, so every occurrence of the other is missed. You can make this happen with a tiny modulus such as mod=7 and two different 3-letter patterns that hash to the same residue. Fix it by mapping each hash to a set of patterns.
Exercise
You scan n = 5×10^7 characters for k = 2×10^5 patterns of length 12, using one modulus p ≈ 2^31. Estimate the expected number of false-positive verifications, and suggest a change if the number is too high.
Show answer
About nk/p = (5×10^7 × 2×10^5) / 2.1×10^9 ≈ 4.7×10^3 false positives, each costing about 12 character comparisons. That is cheap here, but the count grows linearly with k. To push it close to zero, use a modulus near 2^61 or double hashing with the pair (h1, h2) as the dictionary key. Either gives an effective p around 10^18.
Exercise
Change find_any so it returns a dictionary mapping each pattern to its number of occurrences, with patterns that never occur mapped to 0.
Show answer
Initialize counts = {p: 0 for p in patterns} after deduplication. In the loop, replace hits.append((i, window)) with counts[window] += 1, and return counts. The rolling and lookup logic stays the same. For the empty or too-long cases, return the all-zero dictionary instead of [].