3.8.9 · D3String Algorithms

Worked examples — Palindrome algorithms — Manacher's algorithm

2,378 words11 min readBack to topic

Before the matrix, one reminder of the vocabulary so no symbol is unearned:

If any of those feels shaky, re-read the parent's derivation. This page assumes only those five.


The scenario matrix

Every input Manacher can face falls into one of these cells. Each worked example below is tagged with the cell(s) it exercises.

Cell What makes it special Why it's a distinct case
A. Odd champion longest palindrome has odd length (aba) center lands on a real char of
B. Even champion longest palindrome has even length (abba) center lands on a # of
C. All-same aaaa… mirror predicts almost everything; expansion fires rarely — the stress test
D. No repeats every char distinct (abcd) every ; degenerate, nothing to reuse
E. Mirror strictly inside (Case A) copy exactly, do not expand
F. Mirror hits wall (Case B) copy the cap , must expand past
G. (outside) fresh center, no info start from , expand from scratch
H. Boundary / single char "", "a" degenerate limits; bounds checks matter
I. Index mapping recover start in the //2 trap that silently corrupts output
J. Counting total palindromic substrings uses per center
K. Word-problem / exam twist applied phrasing proves you can use it, not just run it

The eight examples below hit all cells A–K.


Worked examples

Example 1 — Odd champion, outside-center start (Cells A, G)


Example 2 — Even champion, mirror hits the wall (Cells B, F)


Example 3 — Mirror strictly inside: the speedup you can watch (Cell E)


Example 4 — All-same: the stress test (Cell C)


Example 5 — No repeats: everything degenerate (Cell D, H)


Example 6 — Index mapping: the //2 trap (Cell I)


Example 7 — Counting all palindromic substrings (Cell J)


Example 8 — Word problem / exam twist (Cell K)


Recall Which cell does each trap live in?

Even champion centers on a # — which cell? ::: Cell B "Copy the mirror, skip expansion" — which cell? ::: Cell E (mirror strictly inside) "Mirror predicts too little, must expand past the wall" — which cell? ::: Cell F The //2 when mapping back to s — which cell? ::: Cell I aaaa… stress-testing linearity — which cell? ::: Cell C

See also: Expand Around Center (the baseline Manacher beats), Longest Palindromic Substring (the headline application), Palindromic Tree (Eertree) (an alternative structure), and the amortized-cost argument in Amortized Analysis.