"""Z-algorithm.

Idea
----
``z[i]`` is the length of the longest substring starting at i that is also a
prefix of the string. Computing it naively is O(n^2). The Z-algorithm keeps
the rightmost window [left, right) known to match the prefix; inside that
window it reuses earlier answers, and it only compares new characters beyond
``right``. Since ``right`` only moves forward, the total work is linear.

To find a pattern P in a text T, compute the Z-array of P + sep + T, using a
separator that appears in neither: every position with z == len(P) is a match.

Complexity
----------
Time:  O(n)
Space: O(n)
"""


def z_array(s: str) -> list[int]:
    n = len(s)
    z = [0] * n
    if n:
        z[0] = n
    left = right = 0
    for i in range(1, n):
        if i < right:
            z[i] = min(right - i, z[i - left])
        while i + z[i] < n and s[z[i]] == s[i + z[i]]:
            z[i] += 1
        if i + z[i] > right:
            left, right = i, i + z[i]
    return z


def z_search(text: str, pattern: str) -> list[int]:
    """Return every start index of ``pattern`` in ``text``."""
    if not pattern:
        return list(range(len(text) + 1))
    combined = pattern + "\x00" + text
    m = len(pattern)
    return [i - m - 1 for i, v in enumerate(z_array(combined)) if i > m and v >= m]
