Rabin Karp Rolling Hash Pattern Match (Python)
Find all occurrences of a pattern in text using Rabin Karp with a rolling hash for O(n+m) average time.
Code
def rabin_karp(text, pattern):
base, mod = 256, 101
n, m = len(text), len(pattern)
if m == 0 or m > n:
return []
pat_hash = txt_hash = 0
h = 1
for i in range(m - 1):
h = (h * base) % mod
for i in range(m):
pat_hash = (pat_hash * base + ord(pattern[i])) % mod
txt_hash = (txt_hash * base + ord(text[i])) % mod
result = []
for i in range(n - m + 1):
if pat_hash == txt_hash and text[i:i + m] == pattern:
result.append(i)
if i < n - m:
txt_hash = (base * (txt_hash - ord(text[i]) * h) + ord(text[i + m])) % mod
if txt_hash < 0:
txt_hash += mod
return resultHow the snippet works
Count the function rabin_karp as the entire surface area of Rabin Karp Rolling Hash Pattern Match (Python).
Repetition is confined to for i in range(m - 1) — the rest of the file is straight-line.
The return value is newly constructed — inputs are never handed back.
Using it
The main signature reads def rabin_karp(text, pattern)
Import rabin_karp from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does `rabin_karp` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `rabin_karp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.