Algorithms · Visualized
String: Manacher
String Matching
Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.
Manacher's algorithm finds the longest palindromic substring in linear time. Time: O(n) average, O(n) worst; space: O(n) for the transformed string and radii.
Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.
Manacher's Algorithm
String MatchingManacher's algorithm finds the longest palindromic substring in linear time. It inserts '#' separators so every palindrome is odd-length around a center, then computes a radius for each center while reusing the already-computed mirror radii inside the rightmost palindrome seen so far — eliminating the O(n²) re-checking of a naive center expansion.
How Manacher Works
- Transform the string by inserting '#' between every character and at both ends.
- Track the center C and right boundary R of the rightmost-reaching palindrome found so far.
- For each center i inside R, initialize its radius from its mirror position 2C−i (capped at R−i) — no comparisons needed.
- Expand beyond the guaranteed inner radius by comparing characters outward.
- Whenever a palindrome extends past R, update C and R, then continue.
Manacher Worked Example
Input: babad
Transform to '#b#a#b#a#d#'. Radii computed left to right, reusing mirror information: at the center between the two b's (transformed index 6), the radius reaches 3, spanning 'bab'. Mirror reuse means most comparisons inside the right boundary are skipped. Converting back gives the original positions of 'bab' (or 'aba') — longest palindromic substring, length 3.
def manacher(s):
t = '#' + '#'.join(s) + '#'
n = len(t)
p = [0] * n
c = r = 0
for i in range(n):
if i < r:
p[i] = min(r - i, p[2 * c - i])
a, b = i + 1 + p[i], i - 1 - p[i]
while b >= 0 and a < n and t[a] == t[b]:
p[i] += 1
a += 1
b -= 1
if i + p[i] > r:
c, r = i, i + p[i]
best, bc = 0, 0
for i in range(n):
if p[i] > best:
best, bc = p[i], i
start = (bc - best) // 2
return s[start:start + best]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Manacher Time & Space Complexity
When to Use Manacher
- DNA palindrome detection (restriction sites).
- Text processing and longest-palindrome interview problems.
- Compression schemes that exploit palindromic redundancy.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.