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.

PythonData Fetching

Code

snippet
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 result