"""Manacher's algorithm: longest palindromic substring in linear time.

Idea
----
Insert a separator between characters ("abba" -> "^#a#b#b#a#$") so every
palindrome has odd length and a single centre. Let ``radius[i]`` be how far
the palindrome centred at i extends. Keep the palindrome reaching furthest to
the right, with centre ``c`` and right edge ``r``. For a new centre i < r, its
mirror ``2c - i`` already has a radius, and by symmetry i's radius is at
least ``min(r - i, radius[mirror])``. Only expand beyond that. The right edge
only moves forward, so the total work is O(n).

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

Compare with ``longest_palindromic_substring.py``, which is O(n^2) but simpler.
"""


def manacher(s: str) -> str:
    """Return the longest palindromic substring (leftmost on ties)."""
    if not s:
        return ""
    t = "^#" + "#".join(s) + "#$"  # sentinels ^ and $ stop expansion
    radius = [0] * len(t)
    centre = right = 0
    for i in range(1, len(t) - 1):
        if i < right:
            radius[i] = min(right - i, radius[2 * centre - i])
        while t[i + radius[i] + 1] == t[i - radius[i] - 1]:
            radius[i] += 1
        if i + radius[i] > right:
            centre, right = i, i + radius[i]
    best_len, best_centre = max((r, -i) for i, r in enumerate(radius))
    start = (-best_centre - best_len) // 2
    return s[start : start + best_len]
