Manacher's Algorithm
An optimal algorithm for finding the longest palindromic substring in linear time. Invented by Glenn K. Manacher in 1975, it cleverly avoids redundant comparisons by utilizing previously computed palindrome information, achieving O(n) time complexity which is optimal for this problem.
Visualization
Interactive visualization for Manacher's Algorithm
Manacher's Algorithm (Longest Palindrome)
• Time: O(n) linear time!
• Finds longest palindromic substring
• Uses center expansion with clever reuse
Interactive visualization with step-by-step execution
Implementation
1function manacher(s: string): string {
2 // Transform string to handle even-length palindromes
3 const t = '#' + s.split('').join('#') + '#';
4 const n = t.length;
5 const p: number[] = Array(n).fill(0);
6 let center = 0, right = 0;
7 let maxLen = 0, maxCenter = 0;
8
9 for (let i = 0; i < n; i++) {
10 const mirror = 2 * center - i;
11
12 if (i < right) {
13 p[i] = Math.min(right - i, p[mirror]);
14 }
15
16 // Expand around center i
17 while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 &&
18 t[i + p[i] + 1] === t[i - p[i] - 1]) {
19 p[i]++;
20 }
21
22 // Update center and right boundary
23 if (i + p[i] > right) {
24 center = i;
25 right = i + p[i];
26 }
27
28 // Track maximum palindrome
29 if (p[i] > maxLen) {
30 maxLen = p[i];
31 maxCenter = i;
32 }
33 }
34
35 const start = (maxCenter - maxLen) / 2;
36 return s.substring(start, start + maxLen);
37}Complexity
Time
O(n)
O(n)
O(n)
Space
O(n)
Applications
Use Cases
Related Algorithms
Knuth-Morris-Pratt (KMP) Algorithm
An efficient string pattern matching algorithm that searches for occurrences of a 'word' within a 'text' by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin. Developed by Donald Knuth, Vaughan Pratt, and James H. Morris in 1977, it's one of the most important string algorithms with O(n+m) time complexity.
Rabin-Karp Algorithm
A string-searching algorithm that uses hashing to find pattern(s) in a text. Developed by Michael O. Rabin and Richard M. Karp in 1987, it's particularly useful for multiple pattern search and plagiarism detection. Uses rolling hash for efficiency.
Boyer-Moore Algorithm
One of the most efficient string searching algorithms in practice, using two heuristics: bad character rule and good suffix rule. Developed by Robert S. Boyer and J Strother Moore in 1977, it's the standard benchmark for practical string search, often outperforming other algorithms by skipping sections of text.
Aho-Corasick Algorithm
A string-searching algorithm for locating elements of a finite set of strings (dictionary) within an input text. Invented by Alfred V. Aho and Margaret J. Corasick in 1975, it's a kind of dictionary-matching algorithm that simultaneously searches for all patterns in linear time, making it extremely efficient for multiple pattern matching.