Algo-Sim › String Algorithms
Longest Palindromic Substring (Manacher)
Medium · String Algorithms · step through it in Java, Python and C++ on your own input
Longest palindrome in O(n): separate letters with #, then start each center’s radius from its mirror inside the rightmost palindrome and only expand past it.
Problem
Given a string s, return its longest contiguous substring that reads the same forwards and backwards. Manacher's algorithm finds it in linear time by reusing the radius of a mirrored centre.
Constraints
- 1 ≤ s.length ≤ 1000
- s contains digits and English letters
- Expanding around every centre is O(n²); Manacher is O(n)
Edge cases to test
- One character
- Even-length palindromes:
"abba" - All the same letter
Follow-up questions
- What is the simpler O(n²) method?
- Expand around each of the 2n − 1 centers: O(n²) time, O(1) space, usually fine in an interview.
- How do you count every palindromic substring?
- A center’s longest palindrome also counts every shorter one around the same center, so summing the per-center counts from Manacher’s radii gives the total in O(n) (LC 647).
Solution
Java
public String longestPalindrome(String s) {
StringBuilder sb = new StringBuilder("#");
for (char c : s.toCharArray()) sb.append(c).append('#');
char[] t = sb.toString().toCharArray();
int n = t.length;
int[] p = new int[n];
int center = 0, right = 0, best = 0;
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[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;
}
int start = (best - p[best]) / 2;
return s.substring(start, start + p[best]);
}Python
def longest_palindrome(s):
t = "#" + "#".join(s) + "#"
n = len(t)
p = [0] * n
center = right = best = 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]
if p[i] > p[best]:
best = i
start = (best - p[best]) // 2
return s[start:start + p[best]]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string longestPalindrome(string &s) {
string sb = "#";
for (char c : s) {
sb += c;
sb += '#';
}
string t = sb;
int n = int(t.size());
vector<int> p = vector<int>(n);
int center = 0, right = 0, best = 0;
for (int i = 0; i < n; i++) {
if (i < right)
p[i] = std::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;
}
int start = (best - p[best]) / 2;
return s.substr(start, (start + p[best]) - (start));
}
};