Manacher's Algorithm (Geeks for Geeks)
1. What is Manacher's Algorithm?​
Manacher's Algorithm is an efficient algorithm used to find the longest palindromic substring in a given string. It operates in linear time, making it significantly faster than the traditional approach which operates in quadratic time.
2. Algorithm for Manacher's Algorithm​
- Preprocess the string to handle even-length palindromes by inserting a unique character (e.g.,
#
) between every character and at the boundaries. - Use the preprocessed string to compute the length of the palindromes centered at each character using a palindrome expansion approach.
- Track the maximum length palindrome and its center to determine the longest palindromic substring.
3. How does Manacher's Algorithm work?​
- Preprocessing: Convert the string
s
to a new stringt
by inserting a unique character#
between each character ofs
and adding boundary characters at the start and end. - Palindrome Expansion: Use the preprocessed string
t
to compute an arrayp
wherep[i]
gives the length of the palindrome centered att[i]
. - Longest Palindromic Substring: Find the maximum value in the array
p
to get the longest palindromic substring in the original strings
.
4. Problem Description​
Given a text string, implement Manacher's Algorithm to find the longest palindromic substring.
5. Examples​
Example 1:
Input: text = "babad"
Output: "bab" (or "aba")
Example 2:
Input: text = "cbbd"
Output: "bb"
Explanation of Example 1:
- The longest palindromic substring in "babad" is "bab" or "aba".