DrawCode Algorithm Visualizer • String • Hard

Manacher's Algorithm

Tags: String, Palindrome, Linear, Center Expansion

1. One-Liner

Manacher’s algorithm finds the longest palindromic substring (and all odd/even radii) in O(n) by tracking palindrome mirrors around centers and reusing known symmetry.


2. The Problem It Solves

Given S, find the maximum-length substring that reads the same forwards and backwards. Naive center expansion is O(n²); Manacher achieves linear total work with clever reuse.


3. The Core Idea

Insert sentinels (e.g. # between characters) to handle even and odd lengths uniformly. For each center, maintain how far the palindrome reaches; inside a bigger palindrome, mirror a smaller palindrome’s radius unless it hits the boundary.


4. How It Works (Table)

StepWhat Happens
1Transform ST with separators.
2Arrays P[i] = radius of palindrome at i in T.
3Track C (center) and R (right edge of palindrome covering i).
4For each i, set initial P[i] from mirror; expand while chars match; update C,R.

5. Dry Run Example

"aba" → transformed string; centers at middle letters yield radius counts mapping back to length 3 for "aba".


6. Key Properties

PropertyValue
TimeO(n)
SpaceO(n)
OutputLongest length or all maximal palindromes

7. Where It Is Used

DomainUse
DNA / RNAInverted repeats
NLPPalindrome features, symmetry cues
InterviewsCanonical “linear palindrome” solution

8. Interview Tips

Explain sentinel trick and mirror formula P[i] = min(R-i, P[mirror]). Fallback: expand centers O(n²) if time is tight.


9. Comparison with Other Algorithms

ApproachTime
BruteO()
Center expandO()
ManacherO(n)
Hash + binary searchO(n log n)

10. Complexity

MetricValue
TimeO(n)
SpaceO(n)

Implementation Example (PYTHON)

def longest_palindrome(s):
    if not s:
        return ''
    t = '#'.join('^{}
    
  

.format(s))
    n = len(t)
    p = [0] * n
    c = r = 0
    for i in range(1, n - 1):
        mir = 2 * c - i
        if i < r:
            p[i] = min(r - i, p[mir])
        while t[i + p[i] + 1] == t[i - p[i] - 1]:
            p[i] += 1
        if i + p[i] > r:
            c, r = i, i + p[i]
    mx = max(range(n), key=lambda i: p[i])
    return s[(mx - p[mx]) // 2 : (mx + p[mx]) // 2]

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer