"""Rabin-Karp substring search with a rolling hash.

Idea
----
Hash the pattern, then slide a window of the same length over the text,
updating the window's hash in O(1) per step: remove the leading character's
contribution, shift, and add the new character. Only when hashes match do we
compare the actual characters, which protects against hash collisions.

Complexity
----------
Time:  O(n + m) expected, O(n * m) worst case (many collisions)
Space: O(1)

When to use
-----------
Searching for many patterns of the same length at once, plagiarism
detection, and any "compare substrings quickly" problem.
"""

BASE = 256
MOD = 1_000_000_007


def rabin_karp(text: str, pattern: str) -> list[int]:
    """Return every start index where ``pattern`` occurs in ``text``."""
    n, m = len(text), len(pattern)
    if m == 0:
        return list(range(n + 1))
    if m > n:
        return []
    high = pow(BASE, m - 1, MOD)  # weight of the leading character
    p_hash = w_hash = 0
    for i in range(m):
        p_hash = (p_hash * BASE + ord(pattern[i])) % MOD
        w_hash = (w_hash * BASE + ord(text[i])) % MOD
    hits: list[int] = []
    for start in range(n - m + 1):
        if w_hash == p_hash and text[start : start + m] == pattern:
            hits.append(start)
        if start + m < n:
            w_hash = (w_hash - ord(text[start]) * high) % MOD
            w_hash = (w_hash * BASE + ord(text[start + m])) % MOD
    return hits
