Manacher's Algorithm

Find the longest palindrome inside a string in linear time, by letting each position copy what its mirror image already found.

A palindrome is text that reads the same forwards and backwards, such as "level" or "noon". Given a string s, return its longest palindromic substring: the longest run of neighbouring characters of s that is a palindrome. If several have the same length, any one may be returned. Solve it in O(n) time, where n is the length of s, with Manacher's algorithm.

Example 1
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also correct.
Example 2
Input: s = "cbbd"
Output: "bb"
Solution

The Idea

Every palindrome has a middle and grows outwards from it: "bab" is the letter a with a b on each side. So one natural way to find palindromes in "babad" is to stand on each position and spread outwards while the characters on the two sides match. Standing on the a at index 1 gives "bab". Standing on the b at index 2 gives "aba".

Example 2 has a catch. In "cbbd" the answer "bb" has no middle letter: its middle is the gap between the two b's. So gaps are centres too. A neat way to treat both kinds alike is to write a # into every gap and at both ends. "cbbd" becomes "#c#b#b#d#", and "bb" turns into "#b#b#", whose middle is the # between the two b's.

Two more characters go on the outside: ^ at the front and $ at the back. They match nothing else, so the spreading stops at the ends by itself. Call the new string t. For each position i in t, let p[i] be the radius of the palindrome around it: how many characters it reaches on each side.

Spreading from every centre works, but much of it repeats earlier work. A palindrome's right half is a mirror copy of its left half. So when a position sits inside a palindrome found earlier, the same characters already appeared around its mirror image on the left side. Can the search reuse what it learned there?

Look at the picture below. It shows "babad" as t, with each position's index above it and its final radius p below it.

The string ^#b#a#b#a#d#$ with index and p value for each position. The palindrome around position 4 reaches index 7 on the right. Position 6 mirrors position 2 around 4, so p[2] = 1 gives p[6] a start of 1.

The palindrome around position 4 is "#b#a#b#", so it reaches index 7 on the right. Position 6 sits inside it, and position 2 sits the same distance from 4 on the other side: 2 is the mirror of 6. Because "#b#a#b#" reads the same both ways, the characters around 6 match the characters around 2, at least up to index 7.

Position 2 already has p[2] = 1, so position 6 starts at 1 without comparing anything. Spreading from there reaches 3, the palindrome "#a#b#a#", which is "aba" once the # signs are dropped.

So inside a palindrome already found, each position gets a free start from its mirror and only spreads past what is known. That reuse is Manacher's algorithm, and it brings the whole search down to O(n).

Solution Approach

The plain spreading from every centre is the baseline to beat. Turning the mirror idea into code then means settling four things: how t is built, how far a mirror can be trusted, what the spreading costs in total, and how a radius becomes a piece of s.

Spreading from every centre

How slow is the simple way? A string of n letters has 2n - 1 centres: n letters and n - 1 gaps. In a string of n equal letters, such as "aaaaa", each centre spreads until it reaches the nearer end. That adds up to about n²/2 comparisons, which is O(n²).

Building the new string

What exactly goes into t? First ^, then # and a letter for each letter of s, then #$. For n letters that is 2n + 3 characters. Every # matches every other # and never a letter, so the palindromes in t found by spreading always begin and end with a #.

Spreading compares the character just past the left side with the one just past the right side. When a palindrome reaches an end of t, one of those two is ^ or $, which matches nothing, so the loop stops without checking any index. Characters placed only to stop a loop like this are called sentinels.

How far a mirror can be trusted

Which earlier palindrome gives the mirror? The one that reaches furthest right. The code keeps its middle in center and its right edge in right. For a position i left of right, the mirror is 2 * center - i, as far left of center as i is right of it.

The copy only holds up to right, because nothing past it has been looked at. Look at position 8 in the picture. By then the palindrome around 6, "#a#b#a#", reaches furthest, so center is 6 and right is 9. The mirror of 8 is 4, with p[4] = 3, but only 9 - 8 = 1 position on each side of 8 is known. And indeed p[8] is 1: past the edge, t has d at index 10 but b at index 6.

So the start value is min(right - i, p[2 * center - i]): the mirror's radius, capped at the edge, and spreading continues from there.

The total cost of spreading

Why is this linear, when positions still spread? There are two cases. If the mirror's radius is smaller than right - i, the mirror's own palindrome stopped at a mismatch inside the known part, and the same two characters sit around i. So the first comparison fails at once.

Otherwise the start already reaches right, or i is past it, and every comparison that matches pushes the right edge of the palindrome around i one more step past right. right never moves back and cannot pass the end of t. So all positions together make at most 2n + 3 matching comparisons, plus one failing comparison each.

From a radius back to a piece of s

How does a radius in t turn into an answer in s? A palindrome of radius r in t has 2r + 1 characters and begins and ends with #. So r + 1 of them are # signs and r are letters, and p[i] is exactly the palindrome's length in s.

Where does it start? In t, the letter s[k] sits at index 2k + 2. A palindrome with middle c and radius r begins with a # at index c - r, an odd number, and its first letter comes right after. Dividing c - r by 2 with Java's integer division drops the leftover half and gives that letter's k. For "babad": (4 - 3) / 2 = 0, and "bab" starts at index 0.

Java Solution

The method longestPalindrome works in these steps:

  1. First, build t with a StringBuilder named sb: ^, then # and each character of s, then #$.
  2. Create the radius array p, as long as t, and set center and right to 0.
  3. A loop moves i over every position of t except the two sentinels. If i is left of right, p[i] starts at Math.min(right - i, p[2 * center - i]), the mirror's radius capped at the edge. Otherwise it starts at 0.
  4. Inside, a while loop spreads: it compares t.charAt(i + p[i] + 1) with t.charAt(i - p[i] - 1) and adds 1 to p[i] while they match.
  5. If i + p[i] passes right, this palindrome now reaches furthest, so center becomes i and right becomes i + p[i].
  6. A second loop finds the largest radius, best, and its position, bestCenter. It keeps the first position with that radius.
  7. Finally, compute start = (bestCenter - best) / 2 and return s.substring(start, start + best).

The main method runs both examples, then "abba" (an even palindrome that is the whole string), "abacdfgdcaba", "aaaaa", a single letter and the empty string, the last two printed in brackets so an empty result is visible.

Java
public class ManachersAlgorithm {

    public static String longestPalindrome(String s) {
        // "aba" -> "^#a#b#a#$": every palindrome now has a centre position
        StringBuilder sb = new StringBuilder("^");
        for (char c : s.toCharArray()) {
            sb.append('#').append(c);
        }
        String t = sb.append("#$").toString();
        int[] p = new int[t.length()];        // p[i]: radius of the palindrome centred at i
        int center = 0;
        int right = 0;                        // right edge of the rightmost palindrome found
        for (int i = 1; i < t.length() - 1; i++) {
            if (i < right) {
                p[i] = Math.min(right - i, p[2 * center - i]);   // copy from the mirror
            }
            while (t.charAt(i + p[i] + 1) == t.charAt(i - p[i] - 1)) {
                p[i]++;                       // grow past what is already known
            }
            if (i + p[i] > right) {
                center = i;
                right = i + p[i];
            }
        }
        int best = 0;
        int bestCenter = 0;
        for (int i = 1; i < t.length() - 1; i++) {
            if (p[i] > best) {
                best = p[i];
                bestCenter = i;
            }
        }
        int start = (bestCenter - best) / 2;  // map back to an index in s
        return s.substring(start, start + best);
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
        System.out.println(longestPalindrome("cbbd"));
        System.out.println(longestPalindrome("abba"));
        System.out.println(longestPalindrome("abacdfgdcaba"));
        System.out.println(longestPalindrome("aaaaa"));
        System.out.println("[" + longestPalindrome("x") + "]");
        System.out.println("[" + longestPalindrome("") + "]");
    }
}

Running it prints:

Output
bab
bb
abba
aba
aaaaa
[x]
[]

Look at the first line: "bab", not "aba". Both have radius 3 in the picture, at positions 4 and 6, and the second loop keeps the first one it meets. "cbbd" gives "bb" from the # at index 5, between the two b's, and "abba" comes back whole from the # in its middle.

"abacdfgdcaba" starts and ends with "aba", which makes it look almost symmetric. Reversed, though, it reads "abacdgfdcaba", so the whole string is not a palindrome, and the answer is the first "aba". "aaaaa" is one palindrome from end to end.

The last two lines show the smallest inputs. One letter is its own answer, [x]. For the empty string, t is "^#$", every radius stays 0, and s.substring(0, 0) gives the empty result [].

The two sentinels must differ. With $ at both ends, "aba" becomes "$#a#b#a#$". The palindrome around the b then reaches both ends, the two $ signs compare equal, and the while loop reads past the end: running it throws StringIndexOutOfBoundsException: Index 9 out of bounds for length 9.

Complexity

The work is one pass over t, with the spreading counted in total rather than per position, plus one pass to find the largest radius.

  • Time: O(n). t has 2n + 3 positions. At each position, the matching comparisons never outnumber the steps right then moves forward. right never moves back, so there are at most 2n + 3 of them, plus at most one failing comparison per position. Finding best is one more pass.
  • Space: O(n), for the new string t and the radius array p, each 2n + 3 entries long.

The simpler spreading from every centre, in O(n²) time and with no extra string, is on Longest Palindromic Substring.