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 sss
Example 1
Output: "bab"
Explanation: "aba" is also correct.
Example 2
Output: "bb"
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 ##
Two more characters go on the outside: ^$titp[i]
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 tp
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 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 ts
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^#s#$##t#
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^$
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 centerrightiright2 * center - icenteri
The copy only holds up to rightcenterrightp[4] = 3p[8]t
So the start value is min(right - i, p[2 * center - i])
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 - ii
Otherwise the start already reaches rightiirightrightt
From a radius back to a piece of s
How does a radius in tst##p[i]s
Where does it start? In ts[k]#
Java Solution
The method longestPalindrome
- First, build
with at namedStringBuilder :sb , then^ and each character of# , thens .#$ - Create the radius array
, as long asp , and sett andcenter to 0.right - A loop moves
over every position ofi except the two sentinels. Ift is left ofi ,right starts atp[i] , the mirror's radius capped at the edge. Otherwise it starts at 0.Math.min(right - i, p[2 * center - i]) - Inside, a
loop spreads: it compareswhile witht.charAt(i + p[i] + 1) and adds 1 tot.charAt(i - p[i] - 1) while they match.p[i] - If
passesi + p[i] , this palindrome now reaches furthest, soright becomescenter andi becomesright .i + p[i] - A second loop finds the largest radius,
, and its position,best . It keeps the first position with that radius.bestCenter - Finally, compute
and returnstart = (bestCenter - best) / 2 .s.substring(start, start + best)
The main
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:
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 ##
"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]ts.substring(0, 0)[]
The two sentinels must differ. With $$whileStringIndexOutOfBoundsException: Index 9 out of bounds for length 9
Complexity
The work is one pass over t
- Time: O(n).
has 2n + 3 positions. At each position, the matching comparisons never outnumber the stepst then moves forward.right never moves back, so there are at most 2n + 3 of them, plus at most one failing comparison per position. Findingright is one more pass.best - Space: O(n), for the new string
and the radius arrayt , each 2n + 3 entries long.p
The simpler spreading from every centre, in O(n²) time and with no extra string, is on