Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Palindromes: Manacher’s Algorithm & the Eertree

Every palindromic substring in linear time.

A string of length nn can hold about n2/2n^2/2 palindromic substrings, yet at most nn distinct ones, and a single linear pass finds every maximal palindrome. The trick is the one behind KMP and the Z-function: never re-read what you already know, here because a mirror has already told you.

What you’ll learn

  • Describe palindromes by centers and radii, and count palindromic substrings by expanding around centers in O(n+number of palindromes)O(n + \text{number of palindromes}).
  • Prove that Manacher's algorithm computes every maximal palindrome in O(n)O(n) time with the mirror argument.
  • Prove that a string of length nn has at most nn distinct nonempty palindromic substrings.
  • Build the eertree online, and use it for counting, for occurrences and for palindromic factorization through arithmetic progressions of palindromic suffixes.

Centers and radii

A palindrome reads the same in both directions: s=reverse⁡(s)s = \operatorname{reverse}(s). Every palindromic substring has a center: a character (odd length) or the gap between two characters (even length), so a string of length nn has 2n−12n - 1 centers. Around one center the palindromes are nested: if s[c−r..c+r]s[c-r..c+r] is a palindrome, so is every shorter one with the same center. Each center therefore has a single maximal palindrome, and its radius encodes all the others.

Expanding around every center finds them all, at a cost of nn plus one step per palindrome found.

python
def count_palindromes(s):
    n, total = len(s), 0
    for c in range(2 * n - 1):           # centers: characters and gaps
        l, r = c // 2, (c + 1) // 2
        while l >= 0 and r < n and s[l] == s[r]:
            total += 1                   # s[l..r] is a palindrome
            l -= 1
            r += 1
    return total

Every successful expansion finds one palindromic substring occurrence, so the running time is O(n+P)O(n + P), where PP counts them. On an\texttt{a}^n, P=n(n+1)/2P = n(n+1)/2 and the algorithm is quadratic.

Predict before you look

How many palindromic substrings, counted with their positions, does abaaba\texttt{abaaba} have?

Show the answer

11 substrings

Six single letters, aa\texttt{aa} once, aba\texttt{aba} twice (at positions 0 and 3), baab\texttt{baab} once and the whole string once: 6+1+2+1+1=116 + 1 + 2 + 1 + 1 = 11. Only 6 of them are distinct: a\texttt{a}, b\texttt{b}, aa\texttt{aa}, aba\texttt{aba}, baab\texttt{baab} and abaaba\texttt{abaaba}.

Manacher's algorithm

First a trick that unifies the two kinds of centers: interleave a separator, t=#s0#s1#⋯#sn−1#t = \texttt{\#}s_0\texttt{\#}s_1\texttt{\#}\cdots\texttt{\#}s_{n-1}\texttt{\#}, of length 2n+12n + 1. Every palindrome of ss becomes an odd palindrome of tt, centered at a letter if its length is odd and at a #\texttt{\#} if even, and the radius d[i]d[i] of the maximal palindrome of tt centered at ii equals the length of the corresponding maximal palindrome of ss.

Manacher's algorithm (Manacher, 1975) computes every d[i]d[i] from left to right, keeping the palindrome t[l..r]t[l..r] (inclusive) that reaches farthest right.

DerivationThe mirror argument, and linear time
  1. d[i] ≥ min⁡(d[j], r−i)d[i] \ \ge\ \min\big(d[j],\ r - i\big)

    The mirror. For l<i≤rl < i \le r, let j=l+r−ij = l + r - i be the mirror image of ii in the box. Since t[l..r]t[l..r] is a palindrome, the stretch around ii inside the box is the reverse of the stretch around jj, so the palindrome at jj, cut to the box, reappears at ii:

  2. d[j]<r−i ⟹ d[i]=d[j]d[j] < r - i \ \Longrightarrow\ d[i] = d[j]

    Strictly inside: copy. If d[j]<r−id[j] < r - i, the mismatch that ends the palindrome at jj lies inside the box, so its mirror image ends the palindrome at ii at the same radius, with no comparison needed:

  3. #comparisons ≤ (2n+1)+(2n+1)=O(n)\#\text{comparisons} \ \le\ (2n + 1) + (2n + 1) = O(n)

    Reaching the edge: extend. Otherwise d[i]≥r−id[i] \ge r - i, and the algorithm compares characters beyond rr. Every successful comparison pushes the right end rr one step further when the box is updated, rr never moves left and stays below 2n+12n + 1, and each ii adds at most one failed comparison:

python
def manacher(s):
    t = '#' + '#'.join(s) + '#'               # 'aba' -> '#a#b#a#'
    n = len(t)
    d = [0] * n                               # d[i]: radius at i = length of that palindrome in s
    l, r = 0, -1                              # t[l..r]: the rightmost palindrome so far
    for i in range(n):
        k = 0 if i > r else min(d[l + r - i], r - i)   # copy the mirror's radius
        while i - k - 1 >= 0 and i + k + 1 < n and t[i - k - 1] == t[i + k + 1]:
            k += 1
        d[i] = k
        if i + k > r:
            l, r = i - k, i + k
    return d

The longest palindrome of ss has length max⁡id[i]\max_i d[i] and starts at (i−d[i])/2(i - d[i])/2; the number of palindromic substrings is ∑i⌈d[i]/2⌉\sum_i \lceil d[i]/2 \rceil. For abaaba\texttt{abaaba}, d=[0,1,0,3,0,1,6,1,0,3,0,1,0]d = [0,1,0,3,0,1,6,1,0,3,0,1,0]: the 6 at the central #\texttt{\#} is the whole string. The separator need not be absent from ss: it is only ever compared with itself.

Manacher designed the algorithm in 1975 to find a string's shortest palindromic prefix, online. Apostolico, Breslauer and Galil (1995) observed that it computes all maximal palindromes, the form in which it is used today.

Check your understanding

Manacher's algorithm reaches a position ii inside the box [l,r][l, r], with mirror j=l+r−ij = l + r - i, where d[j]=2d[j] = 2 and r−i=5r - i = 5. What is d[i]d[i]?

  1. At least 5; compare characters beyond rr to find out
  2. Exactly 2
  3. At most 2, possibly less
  4. Unknown: the mirror says nothing about ii
Show the answer

B. Exactly 2

The palindrome of radius 2 at jj and the mismatch that ends it both lie strictly inside the box (since 2<52 < 5), and the box is a palindrome, so both are mirrored at ii: d[i]=2d[i] = 2, with no comparison at all.

At most n distinct palindromes

DerivationProof: one new palindrome per character
  1. Pal⁡(sc)∖Pal⁡(s) ⊆ {palindromic suffixes of sc}\operatorname{Pal}(sc) \setminus \operatorname{Pal}(s) \ \subseteq\ \{\text{palindromic suffixes of } sc\}

    Where new palindromes appear. Build ss one character at a time. Appending cc to ss can create new palindromes only among the palindromic suffixes of scsc, since every other substring of scsc is a substring of ss.

  2. u suffix of P ⟹ u prefix of P ⟹ u∈Pal⁡(s)u \text{ suffix of } P \ \Longrightarrow\ u \text{ prefix of } P \ \Longrightarrow\ u \in \operatorname{Pal}(s)

    Shorter ones are old. Let PP be the longest palindromic suffix of scsc and uu a shorter one. Then uu is a suffix of PP; reversing both, reverse⁡(u)=u\operatorname{reverse}(u) = u is a prefix of reverse⁡(P)=P\operatorname{reverse}(P) = P. That occurrence of uu ends before the last character, inside ss:

  3. ∣Pal⁡(s)∣ ≤ n\big|\operatorname{Pal}(s)\big| \ \le\ n

    Count. Each appended character adds at most one new distinct palindrome, its longest palindromic suffix. Over nn characters:

The bound is tight: aaaa\texttt{aaaa} has exactly 4 distinct palindromes, abacaba\texttt{abacaba} has 7, and mississippi\texttt{mississippi} has 11. Strings that reach it are called rich and have their own combinatorial theory (Glen, Justin, Widmer & Zamboni, 2009). Contrast the Θ(n2)\Theta(n^2) palindromic occurrences of an\texttt{a}^n: distinct palindromes are few, which is what makes a data structure holding all of them possible.

The eertree

python
class Eertree:
    def __init__(self):
        self.len = [-1, 0]                # node 0: imaginary root; node 1: empty string
        self.link = [0, 0]                # suffix links
        self.next = [{}, {}]              # edges: next[v][c] = node of c + v + c
        self.s, self.last = [], 1         # last: longest palindromic suffix so far

    def _climb(self, v, i):               # first v on the chain with s[i - len - 1] == s[i]
        while True:
            j = i - self.len[v] - 1
            if j >= 0 and self.s[j] == self.s[i]:
                return v
            v = self.link[v]

    def add(self, c):                     # True if a new palindrome appeared
        self.s.append(c)
        i = len(self.s) - 1
        v = self._climb(self.last, i)
        if c in self.next[v]:
            self.last = self.next[v][c]
            return False
        w = len(self.len)
        self.len.append(self.len[v] + 2)
        self.next.append({})
        self.link.append(1 if self.len[w] == 1 else self.next[self._climb(self.link[v], i)][c])
        self.next[v][c] = w
        self.last = w
        return True

To append cc at position ii, climb the suffix links from the longest palindromic suffix until a palindrome vv is preceded by cc; then cvccvc is the new longest palindromic suffix. The imaginary root, of length −1-1, always qualifies, which yields the single letter cc. A new node's suffix link comes from a second climb that starts one step further down the chain.

A potential argument on the suffix-link depth of last shows that all climbs together take O(n)O(n) steps (Rubinchik & Shur), so the construction runs in O(n)O(n) time for a constant alphabet, or O(nlog⁡σ)O(n \log \sigma) with balanced search trees for the children. And it is online: after each character, the tree describes all palindromes of the prefix read so far.

What it answers:

  • Distinct palindromes: the number of nodes minus 2.
  • Occurrences of each palindrome: count how often each node becomes last, then add each node's count to its suffix link, from longer palindromes to shorter ones, the same push-down as for prefix occurrences in The Prefix Function & Z-Function in Depth.
  • Palindromic suffixes of each prefix: the depth of last in the suffix-link tree; their sum over all prefixes is the number of palindromic occurrences.

Palindromic factorization, and the frontier

The palindromic length of ss is the fewest palindromes whose concatenation is ss. For example, abaab\texttt{abaab} is not a palindrome, but a⋅baab\texttt{a} \cdot \texttt{baab} splits it into two, while the greedy aba⋅a⋅b\texttt{aba} \cdot \texttt{a} \cdot \texttt{b} uses three. A dynamic program over prefixes takes, for each prefix, one more than the best over its palindromic suffixes: pl(s[0..i))=1+min⁡upl(s[0..i−∣u∣))\mathrm{pl}(s[0..i)) = 1 + \min_u \mathrm{pl}(s[0..i - \abs u)) over palindromic suffixes uu of s[0..i)s[0..i). A prefix can have Θ(n)\Theta(n) palindromic suffixes (an\texttt{a}^n has ii), so this is Θ(n2)\Theta(n^2), unless the suffixes have structure. They do.

DerivationProof
  1. {palindromic proper suffixes of P}={borders of P},d=per⁡(P)\{\text{palindromic proper suffixes of } P\} = \{\text{borders of } P\}, \qquad d = \operatorname{per}(P)

    Borders of a palindrome are its palindromic suffixes. A suffix uu of the palindrome PP is, reversed, a prefix of PP; so a palindromic suffix is a border, and conversely a border BB and its reverse are both suffixes of length ∣B∣\abs B, hence equal. So QQ is the longest border, and dd is the shortest period of PP:

  2. ∣P∣−d, ∣P∣−2d, …(while≥∣P∣/2)\abs P - d,\ \abs P - 2d,\ \dots \quad (\text{while} \ge \abs P/2)

    Short periods are multiples of dd. If q≤∣P∣/2q \le \abs P/2 is a period, then d+q≤∣P∣d + q \le \abs P, so the Fine–Wilf lemma (weak form) makes gcd⁡(d,q)\gcd(d, q) a period; as dd is the shortest, dd divides qq. Multiples of a period are periods. So the periods up to ∣P∣/2\abs P/2 are exactly d,2d,3d,…d, 2d, 3d, \dots, and the borders of length at least ∣P∣/2\abs P/2 are

  3. ∣P∣>2∣P′∣>4∣P′′∣>⋯⟹#progressions≤log⁡2n+1\abs{P} > 2\abs{P'} > 4\abs{P''} > \cdots \quad\Longrightarrow\quad \#\text{progressions} \le \log_2 n + 1

    Halve and repeat. Every remaining palindromic suffix is shorter than ∣P∣/2\abs P/2, and they are the palindromic suffixes of the longest of them, P′P' with ∣P′∣<∣P∣/2\abs{P'} < \abs P/2. Apply the same argument to P′P': each progression at least halves the length, so at most log⁡2n+1\log_2 n + 1 progressions occur:

Series links in the eertree jump from each progression to the next. The dynamic program can then process a whole progression in O(1)O(1), because the same progression, shifted by its difference dd, was already processed dd characters earlier, and its minimum can be stored on the node. That gives palindromic length in O(nlog⁡n)O(n \log n) time (Fici, Gagie, Kärkkäinen & Kempa, 2014; independently I, Sugimoto, Inenaga, Bannai & Takeda, 2014). Borozdin, Kosolobov, Rubinchik and Shur (2017) brought it down to O(n)O(n) online, though with a large constant that keeps the O(nlog⁡n)O(n \log n) method faster in practice.

Key takeaways

  • Palindromes nest around 2n−12n - 1 centers; expanding around each center costs O(n)O(n) plus one step per palindromic occurrence, which is Θ(n2)\Theta(n^2) on an\texttt{a}^n.
  • Manacher's algorithm mirrors radii inside the rightmost palindrome: d[i]≥min⁡(d[j],r−i)d[i] \ge \min(d[j], r - i), with equality when d[j]<r−id[j] < r - i; since rr only grows, all maximal palindromes take O(n)O(n), and interleaving separators unifies even and odd centers.
  • A string of length nn has at most nn distinct nonempty palindromes, because each new character adds at most one: its longest palindromic suffix.
  • The eertree stores those palindromes, at most n+2n + 2 nodes with its two roots, with edges v→cvcv \to cvc and suffix links; built online in O(nlog⁡σ)O(n \log\sigma), it counts distinct palindromes, their occurrences and the palindromic suffixes of every prefix.
  • The palindromic suffixes of a string form at most log⁡2n+1\log_2 n + 1 arithmetic progressions (borders of a palindrome are its palindromic suffixes, plus Fine–Wilf), which gives palindromic factorization in O(nlog⁡n)O(n \log n); linear time is possible.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What is the largest number of distinct nonempty palindromic substrings a string of length 10 can have?

  1. 55
  2. 11
  3. 20
  4. 10
Show the answer

D. 10

Each new character adds at most one new palindrome, its longest palindromic suffix, so a string of length 10 has at most 10; aaaaaaaaaa\texttt{aaaaaaaaaa} reaches it. The count 55 is the number of palindromic occurrences in a10\texttt{a}^{10}, which repeat.

Question 2

Why does Manacher's algorithm interleave a separator such as # between the characters?

  1. To make every palindrome odd, so even-length ones get a center character too
  2. Because the separator must not occur in the string
  3. To double the running time for safety
  4. To mark where the longest palindrome starts
Show the answer

A. To make every palindrome odd, so even-length ones get a center character too

In #a#b#b#a#\texttt{\#a\#b\#b\#a\#}, the even palindrome abba\texttt{abba} becomes #a#b#b#a#\texttt{\#a\#b\#b\#a\#}, centered at the middle #\texttt{\#}. One loop then handles both kinds of centers, and the radius in tt equals the length in ss.

Question 3

At most how many nodes does the eertree of a string of length 20 have, counting its two roots?

  1. 20
  2. 40
  3. 22
  4. 210
Show the answer

C. 22

One node per distinct nonempty palindrome, at most 20 of them, plus the imaginary root (length −1-1) and the empty root (length 0).

Question 4

Why does the palindromic-length dynamic program drop from Θ(n2)\Theta(n^2) to O(nlog⁡n)O(n \log n) with series links?

  1. Because a string has only O(log⁡n)O(\log n) palindromic suffixes
  2. Because Manacher's algorithm gives the answer directly
  3. Because only the longest palindromic suffix needs to be tried
  4. Because the palindromic suffixes of each prefix form O(log⁡n)O(\log n) arithmetic progressions, and each progression can be handled in O(1)O(1) using values stored when its shifted copy was processed
Show the answer

D. Because the palindromic suffixes of each prefix form O(log⁡n)O(\log n) arithmetic progressions, and each progression can be handled in O(1)O(1) using values stored when its shifted copy was processed

an\texttt{a}^n has ii palindromic suffixes at position ii, but their lengths form a single progression. The Fine–Wilf argument bounds the number of progressions by about log⁡2n\log_2 n, and the minimum over each one is maintained on the eertree node of its longest member.

Further reading

  • G. Manacher, "A new linear-time 'on-line' algorithm for finding the smallest initial palindrome of a string," Journal of the ACM 22(3) (1975), 346–351.
  • M. Rubinchik & A. M. Shur, "EERTREE: An efficient data structure for processing palindromes in strings," European Journal of Combinatorics 68 (2018), 249–265 (IWOCA 2015).
  • G. Fici, T. Gagie, J. Kärkkäinen & D. Kempa, "A subquadratic algorithm for minimum palindromic factorization," Journal of Discrete Algorithms 28 (2014), 41–48.
  • K. Borozdin, D. Kosolobov, M. Rubinchik & A. M. Shur, "Palindromic length in linear time," Proceedings of CPM (2017), 23:1–23:12.
  • D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997).