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

pythonsnippet
21 lines
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

How 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

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.