Sub topic 12
Searching for Many Patterns of the Same Length
This chapter assumes you already know the polynomial hash, the rolling update, and single-pattern Rabin-Karp with match verification from earlier chapters. It also assumes you know that Python dictionaries and sets have expected O(1) lookup.
The Problem with Repeating the Search
Suppose you need to find any of k banned words in a long text of length n. If you run Rabin-Karp once per word, you scan the text k times, which costs O(k·n). When k is in the thousands, that cost adds up quickly.
The rolling hash gives you a better option. Within one pass, the hash of each window depends only on the text. It does not depend on which pattern you are looking for. If every pattern has the same length m, you can compute each window hash once and check it against all patterns at the same time.
Replacing Comparison with Lookup
The single-pattern version asks "does the window hash equal p_hash?" The multi-pattern version asks "is the window hash in this table of pattern hashes?" A dictionary answers that question in expected O(1) time, no matter how many patterns it holds.
Each dictionary value is a set of patterns, not a single pattern. Two different patterns can hash to the same value, and a set keeps both. Verification checks the window text against that set, so collisions never produce false matches.
The Implementation
def find_any(text, patterns, base=256, mod=1_000_000_007):
m = len(next(iter(patterns)))
assert all(len(p) == m for p in patterns)
if m == 0 or m > len(text):
return []
def h(s):
v = 0
for ch in s:
v = (v * base + ord(ch)) % mod
return v
wanted = {}
for pat in patterns:
wanted.setdefault(h(pat), set()).add(pat)
high = pow(base, m - 1, mod)
t = h(text[:m])
hits = []
for i in range(len(text) - m + 1):
if t in wanted and text[i:i + m] in wanted[t]:
hits.append((i, text[i:i + m]))
if i < len(text) - 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')]The text[i:i + m] in wanted[t] check hashes the slice and compares strings. It runs only when the window hash is already in the table, so on typical input it runs rarely.
Cost
| Step | Expected cost |
|---|---|
| Hash all k patterns | O(k·m) |
| Roll over the text | O(n) |
| Verify actual hits | O(m) per hit |
The total is O(k·m + n + h·m) expected, where h is the number of verified matches. Compare that with O(k·n) for k separate searches.
Common Errors
- Mixed pattern lengths. The window has one fixed width, so a 3-letter pattern and a 5-letter pattern cannot share a pass. Group the patterns by length and do one pass per distinct length.
- Storing one pattern per hash.
wanted[h(pat)] = patoverwrites a colliding pattern, and you silently miss its matches. - Skipping verification. With thousands of patterns, a spurious hash hit becomes more likely, because each window has k chances to collide instead of one.
Exercise
You have 10,000 patterns: half have length 4 and half have length 7. How do you adapt find_any, and how many passes over the text do you need?
Show answer
Group the patterns by length and call find_any once per group, then merge the results. That makes two passes, one with m = 4 and one with m = 7, for expected O(2n) scanning plus pattern hashing, compared with 10,000 passes for separate searches.
Exercise
With modulus about 10^9 and k = 10^5 patterns, roughly what is the chance that a given non-matching window hits some pattern hash, and why does that matter?
Show answer
About k/mod = 10^5 / 10^9 = 10^-4 per window. Over a text of 10^7 windows, you should expect around 1,000 spurious hits. Each one costs an O(m) verification, so a larger modulus or double hashing becomes worthwhile.