The user wants a program that implements Manacher's algorithm for finding palindromes.
1. Understand the Goal:
The core task is to implement Manacher's Algorithm.
The goal of the algorithm is to find the longest palindromic substring in a given string in O(N) time complexity.
I need to provide a clear implementation, likely in a popular language like Python or C++. Python is usually preferred for readability, but C++ shows performance characteristics better. I'll provide the solution in Python as it's generally more accessible for algorithmic demonstrations, but I can add C++ or Java if requested. Let's stick to Python for the primary example, maybe add C++ as a secondary for completeness. Let's just do Python for now unless I see a reason not to.
2. Algorithm Logic Refresher:
Preprocessing: The algorithm handles odd and even length palindromes by inserting a separator character (like '#') between every character and at the start/end.
Example: "abba" -> "^#a#b#b#a#$" (or just "#a#b#b#a#").
Boundaries are often added (like ^ and $) to prevent index out of bounds errors, but simple condition checks work too.
Variables:
P (or Len): An array to store the length of the palindrome radius at each center.
C: The center of the current palindrome.
R: The right boundary of the current palindrome (the index of the character after the last character of the palindrome).
Core Loop:
Iterate through the transformed string T using index i.
Mirror Logic: If i < R, we can use the mirror index mirr = 2*C - i to initialize P[i] = min(R - i, P[mirr]). This avoids re-computing known parts.
Expansion: Attempt to expand the palindrome centered at i beyond the current R. Compare T[i + (1 + P[i])] with T[i - (1 + P[i])].
Update: If the expansion goes past R, update C = i and R = i + P[i].
Post-processing: Find the maximum value in P to determine the longest palindrome. Convert the center and radius back to the original string indices.
3. Drafting the Code Structure (Python):
python
def manachers_algorithm(s):
# 1. Preprocess string
# Add separators and boundaries
# E.g., "abc" -> "^#a#b#c#$"
T = '#'.join('^{}$'.format(s))
n = len(T)
P = [0] * n
C = R = 0
for i in range(1, n - 1):
# Mirror calculation
mirr = 2 * C - i
# Optimization
if i < R:
P[i] = min(R - i, P[mirr])
# Attempt to expand
while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
P[i] += 1
# Update Center and Right Boundary
if i + P[i] > R:
C = i
R = i + P[i]
# Find max element in P
max_len = max(P)
center_index = P.index(max_len)
# Extract string
# Need to calculate start index in original string s
# The transformation adds characters.
# If T index is `center_index` and radius is `max_len`,
# The actual characters in T are from (center_index - max_len) to (center_index + max_len)
# Removing '#'s gives us the string.
start = (center_index - max_len) // 2
end = start + max_len
return s[start:end]
4. Refinement & Explanation:
The implementation above is standard.
I need to explain why it works briefly (transformations, mirror property, center/right boundary).
I should provide an example usage.
Complexity analysis (O(N) time, O(N) space) is crucial.
5. Double Check Details:
Boundaries: Using ^ and $ is a smart trick because ^ != $, preventing the expansion loop from going out of bounds. Without them, I'd need if checks inside the while loop.
Index Calculation:
Original: abc
Transformed: ^#a#b#c#$
Indices: 012345678
If max radius is 1 (char 'a'), center is 3. 3 - 1 = 2, 3 + 1 = 4. Substring in T: #a#.
start in original: (3 - 1) // 2 = 2 // 2 = 1. That's wrong. 'a' is at index 0.
Let's re-verify index mapping.
T = ^#a#b#c#$
a is at index 3.
Radius P[3] will be 1.
(3 - 1) // 2 = 1. Wait, a is index 0 in abc.
Ah, ^ is index 0. # is 1. a is 2.
T = '#' .join('^{}$'.format(s))
s = "abba" -> ^#a#b#b#a#$
Indices: 01234567890
Center b (at index 2 in abba) corresponds to index 5 in T? No.
T: ^ (0), # (1), a (2), # (3), b (4), # (5)...
Let's trace s="aba".
T: ^ # a # b # a # $
i: 0 1 2 3 4 5 6 7 8
Max palindrome is 'aba'. Center is b (index 4 in T). Radius = 3.
This requires boundary checks i + P[i] + 1 < n in the while loop.
Using ^ and $ makes the code cleaner.
6. Code Structure for Output:
Definition of longest_palindrome(s).
Docstring explaining inputs/outputs.
The logic derived in step 3.
A main block to demonstrate usage.
Comments explaining the steps.
7. Final Polish:
Ensure the variable names are meaningful (center, right_boundary, radius).
Mention time complexity clearly.
Let's write the actual response.
Self-Correction during drafting:
Some implementations separate odd and even cases or don't use sentinel characters. The standard robust implementation uses the transformed string approach. I will stick to that.
Indexing verification again:
String s length N.
String T length 2N+3 (sentinels).
If max_len is found at center_index with radius max_len.
Substring in T is from center_index - max_len to center_index + max_len.
These indices are in T.
We want indices in s.
Because T looks like ^ # s[0] # s[1] # ..., every character in s is at an even index in T (ignoring ^).
Actually, ^ is 0. # is 1. s[0] is 2. # is 3. s[1] is 4.
So s[i] maps to T[2*i + 2].
Inverse: T[j] maps to s[(j-2)//2].
The formula start = (center_index - max_len) // 2 seems to hold based on the aba trace.
Wait, for ^#a#b#a#$ (indices 0..8).
Max is at index 4 (b). Radius 3.
start = (4 - 3) // 2 = 0.
end = 0 + 3 = 3.
s[0:3] is aba. Correct.
Wait, what about s="bb"?
T = ^#b#b#$.
Indices: 0 1 2 3 4 5 6
Max center is 3 (#). Radius 2.
start = (3 - 2) // 2 = 0.
end = 0 + 2 = 2.
s[0:2] is bb. Correct.
Okay, the logic holds. I will produce the code now.
Here is a complete implementation of Manacher's Algorithm in Python.
This implementation finds the Longest Palindromic Substring in O(N) time and O(N) space.
The Python Code
python
def manachers_algorithm(s):
"""
Finds the longest palindromic substring using Manacher's Algorithm.
Args:
s (str): The input string.
Returns:
str: The longest palindromic substring.
"""
if not s:
return ""
# 1. Preprocessing
# Transform the string to handle even length palindromes.
# We insert '#' between characters and add sentinels '^' at the start
# and '$' at the end to avoid bound checks.
# Example: "abba" -> "^#a#b#b#a#$"
t = "^#" + "#".join(s) + "#$"
n = len(t)
# Array to store palindrome radii
p = [0] * n
# Variables for the algorithm
center = 0 # The center of the current known right-most palindrome
right_bound = 0 # The right boundary of the current palindrome (exclusive or index)
# 2. Iteration
for i in range(1, n - 1):
# Calculate the mirror index of 'i' with respect to 'center'
# mirror = 2 * center - i
mirr = 2 * center - i
# Optimization: If 'i' is within the current right boundary,
# we can use the mirror's value as a starting point.
# We take the minimum of the mirror's radius or the distance to the boundary.
if i < right_bound:
p[i] = min(right_bound - i, p[mirr])
# 3. Expansion
# Attempt to expand palindrome centered at 'i'
# t[i + 1 + p[i]] checks the character to the right
# t[i - 1 - p[i]] checks the character to the left
while t[i + 1 + p[i]] == t[i - 1 - p[i]]:
p[i] += 1
# 4. Update Center and Boundary
# If the expanded palindrome goes past the current right_bound,
# update the center to 'i' and the new right_bound.
if i + p[i] > right_bound:
center = i
right_bound = i + p[i]
# 5. Extract Result
# Find the maximum element in p
max_len = max(p)
center_index = p.index(max_len)
# Calculate the start index in the original string 's'
# original_index = (center_index - max_len) // 2
start_index = (center_index - max_len) // 2
return s[start_index : start_index + max_len]
# --- Usage Example ---
if __name__ == "__main__":
input_str = "babad"
print(f"Input: {input_str}")
result = manachers_algorithm(input_str)
print(f"Longest Palindrome: {result}") # Output could be "bab" or "aba"
input_str_2 = "cbbd"
print(f"Input: {input_str_2}")
result_2 = manachers_algorithm(input_str_2)
print(f"Longest Palindrome: {result_2}") # Output: "bb"
How It Works
Preprocessing (t = "^#a#b#b#a#$"):
Standard algorithms struggle to distinguish between odd-length (e.g., "aba") and even-length (e.g., "abba") palindromes.
Manacher's solves this by inserting a separator character (like #) between every letter. This turns every palindrome into an odd length.
Sentinels (^ and $) are added to the start and end to prevent infinite loops (index out of bounds errors) without needing explicit if checks inside the loop.
The p Array:
This array stores the radius of the palindrome centered at each index i. The radius represents how many characters the palindrome extends outward from the center.
Mirror Property:
The core optimization relies on the fact that if you are inside a large palindrome (bounded by right_bound), the character at index i mirrors a character on the left side (mirr).
You can copy the radius from the mirror position (p[mirr]) instead of calculating from scratch, skipping comparisons for the inner parts of the palindrome.
Complexity:
Time:O(N). The right_bound only moves to the right, ensuring the while loop doesn't run excessively over the whole string.
Space: to store the transformed string and the array.