A palindrome reads the same forwards and backwards, like “racecar” or the Malayalam word “malayalam”. Finding the longest palindrome inside a string is a classic problem. The simple method expands around every possible centre and takes O(n2) time in the worst case. Manacher’s algorithm finds every palindrome in O(n). It reuses what it already knows: inside a big palindrome, the right half mirrors the left half, so many answers can be copied instead of recomputed.
In this lesson you will learn
- Expanding around odd and even centres
- Why expanding is O(n2) in the worst case
- The separator trick that makes every palindrome odd-length
- Mirror positions and the rightmost palindrome
- Mapping the answer back to the original string
You should know strings in C, KMP and the Z algorithm.
Expanding Around Centres
#include <stdio.h>
#include <string.h>
/* Brute force idea: expand around every possible centre.
A palindrome's centre is either a letter (odd length) or a gap (even length). */
int expand(const char *s, int n, int lo, int hi) {
while (lo >= 0 && hi < n && s[lo] == s[hi]) { lo--; hi++; }
return hi - lo - 1; /* length of the palindrome found */
}
void longestByExpanding(const char *s) {
int n = (int)strlen(s), best = 0, start = 0;
for (int c = 0; c < n; c++) {
int odd = expand(s, n, c, c); /* centre on letter c */
int even = expand(s, n, c, c + 1); /* centre between c, c+1 */
int len = odd > even ? odd : even;
if (len > best) { best = len; start = c - (len - 1) / 2; }
}
printf("%-14s longest palindrome \"%.*s\" (length %d)\n", s, best, s + start, best);
}
int main(void) {
longestByExpanding("babad");
longestByExpanding("cbbd");
longestByExpanding("racecar");
longestByExpanding("malayalam");
longestByExpanding("abacdfgdcaba");
return 0;
}
Output
babad longest palindrome "bab" (length 3)
cbbd longest palindrome "bb" (length 2)
racecar longest palindrome "racecar" (length 7)
malayalam longest palindrome "malayalam" (length 9)
abacdfgdcaba longest palindrome "aba" (length 3)
- Every palindrome has a centre. Odd-length palindromes (“bab”) are centred on a letter; even-length ones (“bb”) are centred on the gap between two letters.
expandmoves outwards while the letters on both sides match, then returns the length.- A string of length n has 2n – 1 centres, and each expansion can take up to n steps, so the worst case is O(n2). For a string such as “aaaa…a” every expansion is long.
- When two palindromes tie in length, this code keeps the first one found: “bab” rather than “aba” in “babad”.
Manacher’s Algorithm in O(n)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Manacher's algorithm: all palindromes in O(n).
Step 1: put '#' between letters so every palindrome has odd length:
"abba" -> "^#a#b#b#a#$" (^ and $ are guards that never match) */
int manacher(const char *s, int *bestStart, long *work) {
int n = (int)strlen(s), m = 2 * n + 3;
char *t = malloc(m + 1);
int *p = calloc(m, sizeof *p); /* p[i] = palindrome radius at i in t */
if (!t || !p) { perror("malloc"); exit(1); }
t[0] = '^';
for (int i = 0; i < n; i++) { t[2 * i + 1] = '#'; t[2 * i + 2] = s[i]; }
t[2 * n + 1] = '#'; t[2 * n + 2] = '$'; t[m] = '\0';
int center = 0, right = 0; /* the palindrome reaching furthest right */
*work = 0;
for (int i = 1; i < m - 1; i++) {
int mirror = 2 * center - i;
if (i < right) { /* reuse the mirror's answer: the key trick */
int r = right - i;
p[i] = p[mirror] < r ? p[mirror] : r;
}
while (t[i + p[i] + 1] == t[i - p[i] - 1]) { p[i]++; (*work)++; } /* expand */
if (i + p[i] > right) { center = i; right = i + p[i]; }
}
int best = 0, at = 0;
for (int i = 1; i < m - 1; i++) if (p[i] > best) { best = p[i]; at = i; }
*bestStart = (at - best) / 2; /* map back to an index in s */
free(t); free(p);
return best; /* radius in t = length in s */
}
int main(void) {
const char *words[] = { "babad", "cbbd", "bananas", "abacdfgdcaba" };
int start; long work;
for (int k = 0; k < 4; k++) {
int len = manacher(words[k], &start, &work);
printf("%-18s -> \"%.*s\" (length %d)\n", words[k], len, words[k] + start, len);
}
/* A worst case for expanding: a long run of the same letter */
int n = 20000;
char *big = malloc(n + 1);
if (!big) return 1;
memset(big, 'a', n); big[n] = '\0';
int len = manacher(big, &start, &work);
printf("%d x 'a': longest %d, expansion steps %ld (about n, not n*n)\n", n, len, work);
free(big);
return 0;
}
Output
babad -> "bab" (length 3)
cbbd -> "bb" (length 2)
bananas -> "anana" (length 5)
abacdfgdcaba -> "aba" (length 3)
20000 x 'a': longest 20000, expansion steps 39999 (about n, not n*n)
- Separators: “abba” becomes
^#a#b#b#a#$. Now every palindrome is centred on a character, so one loop handles both odd and even cases.^and$are guards that never match, so expansion stops without bounds checks. p[i]is the radius of the palindrome centred at positioniof the new string. That radius equals the palindrome’s length in the original string.- The algorithm remembers the palindrome that reaches furthest right: its
centerand right edgeright. - If
iis inside that palindrome, its mirror2*center - iis on the left side, and its answer is already known. Positionistarts with at leastmin(p[mirror], right - i), without comparing any letters. - Only then does it try to expand further. Every successful expansion pushes
rightfurther right, andrightnever moves back, so the total work is O(n). - For 20,000 copies of the letter ‘a’, it makes 39,999 expansion steps: about 2n, where the simple method needs about n2/2 = 200 million.
| Method | Time | Extra memory |
|---|---|---|
| Check every substring | O(n3) | O(1) |
| Expand around centres | O(n2) | O(1) |
| Dynamic programming table | O(n2) | O(n2) |
| Manacher’s algorithm | O(n) | O(n) |
Common Mistakes
- Handling only odd-length palindromes and missing answers like “bb”.
- Forgetting the guard characters, so expansion reads past the ends of the array.
- Getting the start index wrong when mapping back: it is
(i - p[i]) / 2in the original string. - Allocating too little memory for the transformed string: it needs 2n + 3 characters plus the terminator.
Practice Exercises
Exercise 1. Write out the transformed string for “aba” and the value of p[i] at its centre.
Show answer
The transformed string is ^#a#b#a#$. The centre is the “b” at index 4. Its palindrome #a#b#a# has radius 3, which is the length of “aba”.
Exercise 2. Using the p array, count all palindromic substrings of a string.
Show answer
long count = 0;
for (int i = 1; i < m - 1; i++) count += (p[i] + 1) / 2;
Each centre with radius r holds (r + 1) / 2 palindromes of the original string, one for each length that fits.
Frequently Asked Questions
Is Manacher’s algorithm worth it over expanding around centres?
For short strings, the simple method is easier and fast enough. For long strings or many queries, such as DNA sequences or competitive programming limits of a million characters, Manacher’s O(n) time makes a large difference.
Can I find the longest palindromic subsequence the same way?
No. A subsequence may skip letters, so it is a different problem. It is solved with dynamic programming, as the LCS of the string and its reverse.
Summary
- Expanding around 2n – 1 centres finds the longest palindrome in O(n2).
- Separators turn every palindrome into an odd-length one centred on a character.
- Mirror positions inside the rightmost palindrome give each new centre a head start.
- Because the right edge only moves forwards, Manacher’s algorithm runs in O(n).
