Manacher's Algorithm
Manacher's Algorithm
Introductionâ
Manacher's Algorithm is an elegant linear-time algorithm that finds the longest palindromic substring in a given string. It was discovered by Glenn K. Manacher in 1975 and achieves O(n) time complexity, making it significantly faster than the naive O(n^3) approach or the dynamic programming O(n^2) approach.
The key insight of the algorithm is to exploit the symmetry property of palindromes to avoid redundant computations.
The Core Insight: Palindromic Symmetryâ
When we find a palindrome centered at some position, we know that the substring immediately to the right (inside the palindrome) has a mirrored counterpart to the left. This symmetry allows us to use previously computed information to skip work.
Algorithm Stepsâ
Step 1: Transform the Stringâ
To handle even-length palindromes uniformly, transform the string by inserting a special character (e.g., '#') between every character and at the boundaries:
Original: "babad"
Transformed: "^#b#a#b#a#d#$"
This ensures all palindromes have a center at a single character.