"""Knuth-Morris-Pratt (KMP) substring search.

Idea
----
When a naive search fails part-way through a match, it throws away what it
learned and restarts one character later. KMP precomputes, for every prefix
of the pattern, the length of the longest proper prefix that is also a
suffix (the "failure" or "prefix function"). On a mismatch it jumps the
pattern forward using that table, so the text pointer never moves backwards.

Complexity
----------
Time:  O(n + m) for text length n and pattern length m
Space: O(m) for the table
"""


def prefix_function(pattern: str) -> list[int]:
    """``pi[i]`` = length of the longest proper prefix of ``pattern[:i+1]``
    that is also a suffix of it."""
    pi = [0] * len(pattern)
    k = 0
    for i in range(1, len(pattern)):
        while k and pattern[i] != pattern[k]:
            k = pi[k - 1]
        if pattern[i] == pattern[k]:
            k += 1
        pi[i] = k
    return pi


def kmp_search(text: str, pattern: str) -> list[int]:
    """Return every start index where ``pattern`` occurs in ``text``."""
    if not pattern:
        return list(range(len(text) + 1))
    pi = prefix_function(pattern)
    hits: list[int] = []
    k = 0
    for i, ch in enumerate(text):
        while k and ch != pattern[k]:
            k = pi[k - 1]
        if ch == pattern[k]:
            k += 1
        if k == len(pattern):
            hits.append(i - k + 1)
            k = pi[k - 1]
    return hits
