"""Longest palindromic substring (expand around centre).

Idea
----
Every palindrome is symmetric around a centre, and there are 2n - 1 centres:
each character (odd length) and each gap between characters (even length).
From each centre, expand outwards while both ends match, and keep the
longest. Manacher's algorithm does this in O(n), but expanding around the
centre is simpler and fast enough for most inputs.

Complexity
----------
Time:  O(n^2)
Space: O(1)
"""


def longest_palindrome(s: str) -> str:
    """Return the longest palindromic substring (leftmost on ties)."""
    if not s:
        return ""
    best_lo, best_hi = 0, 0  # inclusive bounds

    def expand(lo: int, hi: int) -> tuple[int, int]:
        while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
            lo -= 1
            hi += 1
        return lo + 1, hi - 1

    for centre in range(len(s)):
        for lo, hi in (expand(centre, centre), expand(centre, centre + 1)):
            if hi - lo > best_hi - best_lo:
                best_lo, best_hi = lo, hi
    return s[best_lo : best_hi + 1]
