Manacher's Algorithm — Longest Palindromic Substring
Tutorial Video
Text description (accessibility)
This video demonstrates the "Manacher's Algorithm — Longest Palindromic Substring" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Finding the longest palindromic substring naively requires O(n^2) time by expanding from each center. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Finding the longest palindromic substring naively requires O(n^2) time by expanding from each center. Manacher's algorithm finds all palindromic substrings — both odd and even length — in O(n) time by reusing previously computed palindrome radii. This is the canonical O(n) solution to "find the longest palindrome in a string," a classic interview problem with practical applications in DNA analysis (palindromic sequences indicate restriction enzyme sites), text compression, and symmetry detection. The key insight is that palindromes inside a larger known palindrome have known minimum radii, avoiding redundant character comparisons.
🎯 Learning Outcomes
#) to unify odd/even length palindrome handlingp[mirror] = p[i] (limited by the right boundary) as a starting pointCode Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Transformation | flat_map + once | Buffer with character appending |
| Radius array | Vec<usize> | int array |
| Center/right state | Two usize variables | int ref pair |
| Result extraction | p.iter().enumerate().max_by_key() | Array.fold_left for max |
| Char handling | chars() for Unicode | Uchar or byte-level |
| Sentinel choice | # (not in typical ASCII text) | Same; often \000 for bytes |
OCaml Approach
OCaml implements the transformation with Buffer, appending '#' between and around each character. The palindrome radius array is Array.make (2*n+1) 0. Center and right boundary are mutable int ref values. OCaml's pattern matching elegantly handles the three cases: mirror palindrome fits entirely within boundary, mirror radius equals boundary distance, or expansion needed. The String.sub at the end extracts the longest palindromic substring from the original coordinates.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Manacher Palindrome
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.