Learn / Strings

Manacher

Manacher's algorithm finds the longest palindrome around every centre in O(n). It grows palindromes like expand-around-centre, but a centre inside a known palindrome starts from its mirror's answer, so no character is compared twice in a way that costs extra.

How to recognise it

  • The longest palindromic substring, or the number of palindromic substrings, when n is so large that O(n²) is too slow.
  • You need the palindrome radius at every position, not just one answer.

The idea in one picture

Imagine you have already found a long palindrome, like a mirror placed at its centre. For any position on the right half, the mirror shows its twin on the left half, whose palindrome you already measured. You can start from that measurement instead of from zero, and only compare characters beyond the mirror's edge.

Steps

StepWhat happens
1Insert # between characters and at both ends: aba becomes #a#b#a#
2Keep c and r: the centre and right edge of the palindrome reaching furthest right
3For each i, start its radius at min(r - i, radius[2c - i]) if i < r, else at 0
4Grow the radius while the characters on both sides match
5If i + radius passes r, make i the new c

Template

t = "#" + characters of s joined by "#" + "#"
radius = array of len(t) zeros, c = 0, r = 0
for i from 0 to len(t) - 1:
    if i < r: radius[i] = min(r - i, radius[2 * c - i])
    while i - radius[i] - 1 >= 0 and i + radius[i] + 1 < len(t)
          and t[i - radius[i] - 1] == t[i + radius[i] + 1]:
        radius[i] = radius[i] + 1
    if i + radius[i] > r: c = i; r = i + radius[i]

In t, radius[i] is also the length of that palindrome in the original string. The longest one starts at (i - radius[i]) / 2 in s.

When to use it

For most interview problems, expand-around-centre (O(n²), see the Palindromes lesson) is fast enough and much easier to get right. Reach for Manacher when n is around 10⁵ or more, or when you need every radius.

Common mistakes

  • Forgetting the separators, which forces two separate passes for odd and even lengths.
  • Starting a radius at the mirror's value without capping it at r - i.
  • Converting a position in t back to s with the wrong formula.

Problems

No problems listed for this pattern yet.

Check yourself

Why does Manacher's algorithm insert a separator like # between characters?

Position i lies inside the rightmost palindrome found so far, which has centre c and right edge r. Where can the radius at i start?

Why is the total work O(n)?