Lesson 39 · Core algorithms

Manacher's Algorithm

Manacher's algorithm computes the palindrome radius at every centre of a string in O(n) time. Inside a palindrome already found, the right half mirrors the left half, so most radii are copied instead of recomputed.

Manacher's Algorithm concept diagramA visual explanation of the layout and operations shown in this lesson.a known centre mirrors its radius to the right halfa0b1a2c3a4b5a6centremirror i' = 1position i = 5the radius at i' is already known — copy it, then extend only past the boundaryeach character is examined a constant number of times, so the scan is linear
1

What Manacher's Algorithm Does

Manacher's algorithm (Glenn Manacher, 1975) finds, for every position of a string, the longest palindrome centred there. The largest of those answers the classic longest palindromic substring question, and the whole array is built in O(n) time: it finds every palindrome in linear time, as radii.

Growing a palindrome outward from each centre is simple but costs O(n²) on strings like aaaa…a, where every centre grows to the end. The Manacher algorithm gets the same radii with far fewer comparisons because a palindrome is symmetric: whatever is known about its left half is also true of its right half.

  • Output: one radius per centre, O(n) numbers
  • Every palindrome in the string can be read from those radii
2

Radius at Each Centre

With odd centres, d[i] = k means s[i − k + 1 .. i + k − 1] is a palindrome, of length 2k − 1. If a radius-k palindrome sits at i, the radius k − 1, k − 2, … ones do too, so one number stands for all palindromes at that centre. A string can hold Θ(n²) palindromes (aaaa…a), which is why no method that lists them all can be linear; storing radii is what makes linear possible.

The tracer uses s = abaxabaxabb. Its radii are d = [1, 2, 1, 4, 1, 5, 1, 3, 1, 1, 1], and the largest, d[5] = 5, is baxabaxab.

  • Odd length 2k − 1 starts at i − k + 1
  • Largest radius gives the longest palindrome
3

The Mirror Trick

  1. Keep [L, R], the palindrome found so far whose right end R is furthest right
  2. For centre i inside it, find the mirror j = L + R − i
  3. Start with k = min(d[j], R − i + 1); outside [L, R] start with k = 1
  4. Compare s[i − k] with s[i + k] and grow k while they match
  5. If the palindrome at i ends past R, it becomes the new [L, R]

Why the copy is safe. [L, R] reads the same backwards, so the characters around j appear, reflected, around i. If the palindrome at j fits inside [L, R], its reflection fits too and d[i] = d[j] exactly, with no comparison at all.

Why the cap. If the palindrome at j pokes out past L, its reflection would poke out past R, into characters that were never compared. The min with R − i + 1 keeps only the part that is proven, and the loop then checks the rest one pair at a time. In the tracer, centre 7 copies 4 from its mirror, clips to 3, and the next pair (a, b) fails; copying 4 blindly would wrongly call abaxabb a palindrome.

  • Inside [L, R]: copy, clip at R, then expand
  • Outside: expand from radius 1
Key reference

Terms, operations, and practical uses

Radii

  • CentreA character (odd palindromes) or the gap between two characters (even). With # separators every centre is a position.
  • Radius d[i]How far the palindrome at i reaches. With d counting the centre, the length is 2·d[i] − 1.
  • Separator string#a#b#b#a#: 2n + 1 positions, so even palindromes get a centre too.

Mirror reuse

  • Rightmost palindrome [L, R]The palindrome found so far that reaches furthest right. Its symmetry is what gets reused.
  • Mirror centrej = L + R − i, the reflection of i inside [L, R].
  • ClipStart at min(d[j], R − i + 1): copy only what lies inside the proven region.

Results

  • Longest palindromeThe largest radius; start i − k + 1 and length 2k − 1 with odd radii.
  • Palindrome countSum of (p[i] + 1) / 2 over the separator string's centres.
  • Amortised boundMatches move R right, at most n times; one mismatch per centre. Total O(n).
Implementation

Code in Python, C++ and Java

def longest_palindrome(s):
    t = "#" + "#".join(s) + "#"
    n = len(t)
    p = [0] * n
    center = right = 0
    for i in range(n):
        if i < right:
            p[i] = min(right - i, p[2 * center - i])
        while i - p[i] - 1 >= 0 and i + p[i] + 1 < n and 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(n), key=lambda i: p[i])
    start = (best - p[best]) // 2
    return s[start:start + p[best]]


for s in ["abaxabaxabb", "abba", ""]:
    print(f'Longest palindrome in "{s}": "{longest_palindrome(s)}"')
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

string longestPalindrome(const string& s) {
    string t = "#";
    for (char c : s) {
        t += c;
        t += '#';
    }
    int n = t.size(), center = 0, right = 0, best = 0;
    vector<int> p(n, 0);
    for (int i = 0; i < n; i++) {
        if (i < right) p[i] = min(right - i, p[2 * center - i]);
        while (i - p[i] - 1 >= 0 && i + p[i] + 1 < n && t[i - p[i] - 1] == t[i + p[i] + 1]) p[i]++;
        if (i + p[i] > right) {
            center = i;
            right = i + p[i];
        }
        if (p[i] > p[best]) best = i;
    }
    return s.substr((best - p[best]) / 2, p[best]);
}

int main() {
    for (string s : {"abaxabaxabb", "abba", ""})
        cout << "Longest palindrome in \"" << s << "\": \"" << longestPalindrome(s) << "\"\n";
}
public class Main {
    static String longestPalindrome(String s) {
        StringBuilder sb = new StringBuilder("#");
        for (char c : s.toCharArray()) sb.append(c).append('#');
        String t = sb.toString();
        int n = t.length(), center = 0, right = 0, best = 0;
        int[] p = new int[n];
        for (int i = 0; i < n; i++) {
            if (i < right) p[i] = Math.min(right - i, p[2 * center - i]);
            while (i - p[i] - 1 >= 0 && i + p[i] + 1 < n && t.charAt(i - p[i] - 1) == t.charAt(i + p[i] + 1)) p[i]++;
            if (i + p[i] > right) {
                center = i;
                right = i + p[i];
            }
            if (p[i] > p[best]) best = i;
        }
        int start = (best - p[best]) / 2;
        return s.substring(start, start + p[best]);
    }

    public static void main(String[] args) {
        for (String s : new String[] {"abaxabaxabb", "abba", ""})
            System.out.println("Longest palindrome in \"" + s + "\": \"" + longestPalindrome(s) + "\"");
    }
}
Watch it run

Step through it

Running on abaxabaxabb, then abba

s = abaxabaxabb, one radius per centrea0b1a2x3a4b5a6x7a8b9b10dd[i] = k: palindrome of length 2k − 1 centred at iplain expansion from every centre costs O(n²) on aaaa…agoal: fill d[0..10]
Step 1

Odd radius at every centre

Manacher's algorithm fills one number per position: d[i] = k means the k − 1 characters on each side of i mirror each other, so s[i−k+1 .. i+k−1] is a palindrome of length 2k − 1. Every shorter palindrome at the same centre comes for free, so 11 numbers describe all odd palindromes in the string.

Output
1 / 12
4

Why It Runs in Linear Time

Count comparisons in two groups. A successful comparison at centre i always involves a character past R (anything inside was copied), so it pushes R one step right. R starts at −1 and never passes n − 1, so there are at most n successful comparisons in total. Each centre also makes at most one failed comparison, the one that stops it. That gives at most 2n comparisons: O(n) time and O(n) space for the radius array.

This is an amortised argument, like the one for KMP: a single centre can still do many comparisons (centre 5 in the tracer does four), but the total over all centres is bounded because R only moves forward.

  • Every match moves R right
  • At most one mismatch per centre
5

Odd and Even Palindromes

abba has no middle character, so odd radii alone miss it: every d is 1. Two fixes are common. Separators: build t = #a#b#b#a#, length 2n + 1. Every palindrome in t has odd length and a real centre, the gap between the b's becomes index 4, and p[i] (characters on one side, not counting the centre) equals the palindrome's length in s. The start in s is (i − p[i]) / 2.

Two arrays: keep d1 for odd centres and d2 for even centres (between i − 1 and i), each with its own mirror loop. It avoids picking a separator, but doubles the code and the off-by-one risk. The code on this page uses separators; the # never needs to be absent from the input, because separators are only ever compared with each other.

  • Separators: one loop, 2n + 1 positions
  • d1/d2: no extra string, two loops
6

Manacher vs Other Palindrome Methods

For interview limits (n ≤ a few thousand), growing from the 2n − 1 centres is usually enough and shorter to write. Manacher's algorithm earns its place when n reaches 10⁵ or more, or when every radius is needed, for example to count palindromes.

Ways to find the longest palindrome
MethodTimeExtra spaceNote
Check every substringO(n³)O(1)Only for tiny inputs
Grow from each centreO(n²)O(1)Simple; slow on aaaa…a
DP table pal[i][j]O(n²)O(n²)Answers any s[i..j] later
Hashing + binary searchO(n log n)O(n)Small chance of a hash collision
Manacher's algorithmO(n)O(n)Exact; every radius at once
  • Small n: centre growth
  • Large n or all radii: Manacher
7

Counting Palindromes with the Radii

In the separator version, centre i holds (p[i] + 1) / 2 palindromes (integer division): the radii p[i], p[i] − 2, … down to 1 or 2. Summing that over all centres counts every palindromic substring in O(n), which solves Palindromic Substrings without its O(n²) loop. For abba, p = [0, 1, 0, 1, 4, 1, 0, 1, 0] gives 1 + 1 + 2 + 1 + 1 = 6: a, b, b, a, bb, abba.

The radii describe a fixed string. If characters change, the array has to be rebuilt; hashing or a palindromic tree (eertree) suit text that grows or changes. Related string tools: Z algorithm and string hashing.

  • Count = Σ (p[i] + 1) / 2
  • Static strings only
8

Edge Cases and Bugs

Missing the cap copies a radius that reaches past R and reports a palindrome that is not there. Mixing conventions is the most common bug: d counting the centre (length 2k − 1) and p not counting it (length p in s) need different start and length formulas, so keep one convention per file. Bounds: check i − k ≥ 0 and i + k < n before reading characters.

Test the empty string, one character, all-equal text (aaaa), an even-only answer (abba), no palindrome longer than 1 (abc), and ties (pick the first). For Unicode, decide whether you compare bytes, code points or grapheme clusters; a byte-level scan can split a multi-byte character. Cross-check random small strings against centre growth.

  • Always take min(d[j], R − i + 1)
  • One radius convention, one formula