Palindromes: Manacher’s Algorithm & the Eertree
Every palindromic substring in linear time.
A string of length can hold about palindromic substrings, yet at most 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 .
- Prove that Manacher's algorithm computes every maximal palindrome in time with the mirror argument.
- Prove that a string of length has at most 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: . Every palindromic substring has a center: a character (odd length) or the gap between two characters (even length), so a string of length has centers. Around one center the palindromes are nested: if 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 plus one step per palindrome found.
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 totalEvery successful expansion finds one palindromic substring occurrence, so the running time is , where counts them. On , and the algorithm is quadratic.
How many palindromic substrings, counted with their positions, does have?
Show the answer
11 substrings
Six single letters, once, twice (at positions 0 and 3), once and the whole string once: . Only 6 of them are distinct: , , , , and .
Manacher's algorithm
First a trick that unifies the two kinds of centers: interleave a separator, , of length . Every palindrome of becomes an odd palindrome of , centered at a letter if its length is odd and at a if even, and the radius of the maximal palindrome of centered at equals the length of the corresponding maximal palindrome of .
Manacher's algorithm (Manacher, 1975) computes every from left to right, keeping the palindrome (inclusive) that reaches farthest right.
The mirror. For , let be the mirror image of in the box. Since is a palindrome, the stretch around inside the box is the reverse of the stretch around , so the palindrome at , cut to the box, reappears at :
Strictly inside: copy. If , the mismatch that ends the palindrome at lies inside the box, so its mirror image ends the palindrome at at the same radius, with no comparison needed:
Reaching the edge: extend. Otherwise , and the algorithm compares characters beyond . Every successful comparison pushes the right end one step further when the box is updated, never moves left and stays below , and each adds at most one failed comparison:
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 dThe longest palindrome of has length and starts at ; the number of palindromic substrings is . For , : the 6 at the central is the whole string. The separator need not be absent from : 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.
Manacher's algorithm reaches a position inside the box , with mirror , where and . What is ?
- At least 5; compare characters beyond to find out
- Exactly 2
- At most 2, possibly less
- Unknown: the mirror says nothing about
Show the answer
B. Exactly 2
The palindrome of radius 2 at and the mismatch that ends it both lie strictly inside the box (since ), and the box is a palindrome, so both are mirrored at : , with no comparison at all.
At most n distinct palindromes
Where new palindromes appear. Build one character at a time. Appending to can create new palindromes only among the palindromic suffixes of , since every other substring of is a substring of .
Shorter ones are old. Let be the longest palindromic suffix of and a shorter one. Then is a suffix of ; reversing both, is a prefix of . That occurrence of ends before the last character, inside :
Count. Each appended character adds at most one new distinct palindrome, its longest palindromic suffix. Over characters:
The bound is tight: has exactly 4 distinct palindromes, has 7, and has 11. Strings that reach it are called rich and have their own combinatorial theory (Glen, Justin, Widmer & Zamboni, 2009). Contrast the palindromic occurrences of : distinct palindromes are few, which is what makes a data structure holding all of them possible.
The eertree
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 TrueTo append at position , climb the suffix links from the longest palindromic suffix until a palindrome is preceded by ; then is the new longest palindromic suffix. The imaginary root, of length , always qualifies, which yields the single letter . 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 steps (Rubinchik & Shur), so the construction runs in time for a constant alphabet, or 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
lastin the suffix-link tree; their sum over all prefixes is the number of palindromic occurrences.
Palindromic factorization, and the frontier
The palindromic length of is the fewest palindromes whose concatenation is . For example, is not a palindrome, but splits it into two, while the greedy uses three. A dynamic program over prefixes takes, for each prefix, one more than the best over its palindromic suffixes: over palindromic suffixes of . A prefix can have palindromic suffixes ( has ), so this is , unless the suffixes have structure. They do.
Borders of a palindrome are its palindromic suffixes. A suffix of the palindrome is, reversed, a prefix of ; so a palindromic suffix is a border, and conversely a border and its reverse are both suffixes of length , hence equal. So is the longest border, and is the shortest period of :
Short periods are multiples of . If is a period, then , so the Fine–Wilf lemma (weak form) makes a period; as is the shortest, divides . Multiples of a period are periods. So the periods up to are exactly , and the borders of length at least are
Halve and repeat. Every remaining palindromic suffix is shorter than , and they are the palindromic suffixes of the longest of them, with . Apply the same argument to : each progression at least halves the length, so at most progressions occur:
Series links in the eertree jump from each progression to the next. The dynamic program can then process a whole progression in , because the same progression, shifted by its difference , was already processed characters earlier, and its minimum can be stored on the node. That gives palindromic length in 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 online, though with a large constant that keeps the method faster in practice.
Key takeaways
- Palindromes nest around centers; expanding around each center costs plus one step per palindromic occurrence, which is on .
- Manacher's algorithm mirrors radii inside the rightmost palindrome: , with equality when ; since only grows, all maximal palindromes take , and interleaving separators unifies even and odd centers.
- A string of length has at most distinct nonempty palindromes, because each new character adds at most one: its longest palindromic suffix.
- The eertree stores those palindromes, at most nodes with its two roots, with edges and suffix links; built online in , it counts distinct palindromes, their occurrences and the palindromic suffixes of every prefix.
- The palindromic suffixes of a string form at most arithmetic progressions (borders of a palindrome are its palindromic suffixes, plus Fine–Wilf), which gives palindromic factorization in ; linear time is possible.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What is the largest number of distinct nonempty palindromic substrings a string of length 10 can have?
- 55
- 11
- 20
- 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; reaches it. The count 55 is the number of palindromic occurrences in , which repeat.
Why does Manacher's algorithm interleave a separator such as # between the characters?
- To make every palindrome odd, so even-length ones get a center character too
- Because the separator must not occur in the string
- To double the running time for safety
- 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 , the even palindrome becomes , centered at the middle . One loop then handles both kinds of centers, and the radius in equals the length in .
At most how many nodes does the eertree of a string of length 20 have, counting its two roots?
- 20
- 40
- 22
- 210
Show the answer
C. 22
One node per distinct nonempty palindrome, at most 20 of them, plus the imaginary root (length ) and the empty root (length 0).
Why does the palindromic-length dynamic program drop from to with series links?
- Because a string has only palindromic suffixes
- Because Manacher's algorithm gives the answer directly
- Because only the longest palindromic suffix needs to be tried
- Because the palindromic suffixes of each prefix form arithmetic progressions, and each progression can be handled in using values stored when its shifted copy was processed
Show the answer
D. Because the palindromic suffixes of each prefix form arithmetic progressions, and each progression can be handled in using values stored when its shifted copy was processed
has palindromic suffixes at position , but their lengths form a single progression. The Fine–Wilf argument bounds the number of progressions by about , 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).