How Manacher mirrors palindrome radii

Short answer: Manacher’s algorithm finds every palindromic substring’s radius, and in particular the longest one, in O(n) time. It transforms the string so odd and even lengths share one code path, then fills a radius array. A window around the rightmost palindrome found so far mirrors radii across its center. A mirrored value that lies strictly inside the window is copied. A value that meets the window’s edge is verified by expanding.


What the problem actually asks

Every substring can be tested for being a palindrome in time proportional to its length, and there are Θ(n²) substrings. The longest palindromic substring is a common interview target and a real string primitive. Expansion around each center is already O(n²) and easy. Manacher’s observation is the same boxing idea as the Z-algorithm: inside a known palindrome, the radius at the mirror position copies, up to the boundary of the known window.

Even-length palindromes have a center between characters. Inserting a sentinel between characters, and at the ends, makes every palindrome odd in the new string. The sentinels are not part of the answer. They are a coordinate trick.


What the algorithm guarantees

The radius array is filled in O(n) character comparisons. The maximum radius is the longest palindromic substring, mapped back to the original indices by undoing the sentinel insertion. Extra memory is the radius array and the transformed string. The algorithm reports existence and extent. It does not list all palindromes in output-sensitive time by itself, although the radius array encodes all of them and can be walked.

A copied radius larger than the distance to the window edge is illegal. The true radius may be shorter, because the characters outside the window are unknown, or it may continue, which is why equality with the edge falls through to expansion. This is the same case split as the Z-box.


The working steps

  1. Build a transformed string with a sentinel between characters and at both ends. Radii in this string are all odd-centered.
  2. Maintain the center c and the right edge r of the palindrome that currently reaches farthest right.
  3. For each new center i, if i is inside r, set its radius to the minimum of the mirror’s radius and r−i. The mirror is 2c−i.
  4. While the characters just outside the guessed radius match, expand. Then, if i plus its radius passes r, replace c and r with i and that new edge.
  5. The longest palindrome in the original string is the maximum radius, translated back by removing sentinels.

The linear bound is for contiguous palindromic substrings, not for palindromic subsequences. A subsequence can pick non-adjacent characters and is a different dynamic program, quadratic in the usual formulation. Manacher’s array does not approximate. Expansion around centers is the correct quadratic algorithm the window replaces.


Approaches that look simpler and fail

Approach Why it fails when the mirrored radius ignores the window
Copy the mirror radius even when it sticks out of the window Characters beyond r have not been checked. The copied radius has to stop at r, and expansion starts there.
Run the algorithm on the raw string and expect even lengths to appear as odd centers An even palindrome has no character at its center. The sentinel transform, or a second pass with centers between characters, is what covers those lengths.
Quote O(n) for the longest palindromic subsequence Subsequence and substring are different problems. The subsequence DP is quadratic.
Expand every center from scratch and skip the mirror The answer is correct and the time is quadratic. The mirror is the linear bound.

Palindromic subsequences belong to a quadratic DP, related to longest common subsequence of the string and its reverse. Linear palindromic substrings belong to Manacher. The boxing idea is the same one the Z-algorithm uses for prefixes.


A working example

This Python fragment inserts sentinels so an even-length palindrome becomes an odd-length one, then mirrors radii inside the current window. It prints the longest palindrome aba.

def manacher(s):
    t = "^#" + "#".join(s) + "#$"
    p = [0] * len(t)
    center = right = 0
    for i in range(1, len(t) - 1):
        if i < right:
            p[i] = min(right - i, p[2 * center - i])
        while t[i + p[i] + 1] == t[i - p[i] - 1]:
            p[i] += 1
        if i + p[i] > right:
            center, right = i, i + p[i]
    best = max(range(len(p)), key=p.__getitem__)
    start = (best - p[best]) // 2
    return s[start:start + p[best]]

assert manacher("babad") in ("bab", "aba")
print(manacher("babad"))

Where it is used

Manacher’s algorithm finds the longest palindromic substring of a DNA string or a text in linear time. Center expansion is the simple alternative and is quadratic on a long run of the same character. The radius array is the whole output.


When you can drop this algorithm

Drop Manacher when a single center is already known and a short expansion will confirm it. Keep it when every radius, or the longest palindromic substring of a long string, must be computed in linear time.


Why this stays published

We publish this so a search for Manacher’s algorithm returns the mirrored radius and the sentinel trick that unifies odd and even lengths. Manacher’s algorithm computes every palindromic radius in linear time by mirroring radii inside the rightmost known palindrome and expanding only at its edge.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *