Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Strings

Let the Mirror Do the Work.

Don't memorize Manacher's algorithm — watch the mirror do the work. To find the longest palindrome in a string, first slip a separator between every character so every palindrome becomes odd-length, then measure a radius at each center. The magic is a cached rightmost palindrome [C, R]: for a new center inside it, an earlier mirror already knows the answer, so you reuse it for free and only compare fresh characters past the edge. That turns O(n²) into O(n).

insert # separators · radius per center · mirror inside [C, R] · O(n)
LONGEST PALINDROME

The longest substring that reads the same forwards and backwards.

# TRANSFORM

Put a separator between every char so even and odd palindromes are both odd.

RADIUS P[i]

How far the palindrome centered at i reaches — and its length in the original string.

MIRROR + [C, R]

Inside the rightmost palindrome, reuse P[2C − i] instead of expanding again.

manacher.sim — longest palindrome of "abaaba"
Ready

The string is padded to #a#b#a#a#b#a# so every palindrome has a real center. Each P[i] is the palindrome radius there. The amber [C, R] box caches the furthest-right one; inside it we mirror. Press Step.

i < R: P[i] = min(R − i, P[2C − i]); then expand past R
—
Center i
0
Best radius

Two palindromes for the price of one

The naive way to find the longest palindrome is to stand at every possible center and expand outward while the characters match. There are about 2n centers and each can expand up to n, so it is O(n²). Manacher keeps that expand-around-center idea but refuses to redo work. It tracks the palindrome that currently reaches furthest right, as a center C and right edge R. Now consider a new center i sitting inside that window. Everything in [C, R] mirrors around C, so the character pattern at i matches the pattern at its mirror i' = 2C − i — whose radius you already computed. You copy that radius, capped so it cannot poke outside the window (you have no guarantee beyond R), and only then try to expand further. Every successful expansion pushes R right, and R only moves forward, so all the expansions together cost O(n).

01

Transform

Insert # between every character and at the ends, so all palindromes are odd and centered on a real index.

02

Keep the rightmost palindrome

Maintain C and R: the center and right edge of the palindrome reaching furthest right.

03

Mirror, then expand

For i < R, start from P[i] = min(R − i, P[2C − i]), then expand character by character.

04

Slide and finish

If the palindrome at i passes R, set C = i, R = i + P[i]. The max P[i] is the answer.

Time
O(n)
Space
O(n)
Naive
O(n²)
Idea
Mirror + window

To recover the substring, note that in the padded string P[i] equals the palindrome length in the original, and its start is (i − P[i]) / 2. For abaaba the biggest radius is 6, at the central separator — the whole string is a palindrome. Manacher is the palindrome twin of the Z-algorithm: both cache a rightmost matched window and mirror earlier results into it, comparing fresh characters only past the edge. Same linear-time idea, different question — prefix matches there, palindrome radii here.

Check yourself

1 · Why insert # separators before running Manacher?

Separators turn even-length palindromes (centered between chars) into odd ones, so a single center-and-radius method handles both, and the radius maps to the original length.

2 · Inside the [C, R] window, how is P[i] first set?

The mirror position 2C − i already has a radius; you reuse it but cannot trust anything past R, so you cap at R − i, then expand.

3 · Why is the whole algorithm O(n)?

Reuse handles most positions with no comparisons; the only fresh comparisons advance R, which can move forward at most n times total.

The picture: one radius per centre

#00a11#20b33#40a51#64a71#80b91#100 index above, radius P[i] belowcentre 6, radius 4: b a a b
The string abaab after padding with #. The number under each position is the radius P[i] of the palindrome centred there. The highlighted run is the winner: radius 4 at the separator between the two as, which spells baab.

Worked example, step by step

Run it on abaab, which pads to #a#b#a#a#b# (11 positions). The table skips position 0, which is always 0. “Start” is the radius the algorithm assumes before comparing any characters; the bold column is the final radius. [C, R] is the rightmost palindrome after that step.

iCharHow it startsStartP[i][C, R]
1aoutside window01[1, 2]
2#outside window00[1, 2]
3boutside window03[3, 6]
4#mirror 2 has 0; window allows 200[3, 6]
5amirror 1 has 1; window allows 111[3, 6]
6#outside window04[6, 10]
7amirror 5 has 1; window allows 311[6, 10]
8#mirror 4 has 0; window allows 200[6, 10]
9bmirror 3 has 3; window allows 111[6, 10]
10#outside window00[6, 10]

Three behaviours show up. At i = 5 the window [3, 6] covers position 5, its mirror 1 already has radius 1, and the algorithm starts at 1 without a single character check. At i = 6 there is no window left to lean on, so it expands honestly, grows to 4, and the window jumps to [6, 10]. At i = 9 the mirror (position 3) has radius 3 but the window only has 1 position of room, so the start is capped at 1. That cap is the line min(R − i, P[mirror]); without it the radius would be copied past the edge of what is known. Total character comparisons for the whole string: 13. The longest radius is 4 at i = 6, so the answer is baab, found at original index (6 − 4) / 2 = 1.

Complexity and trade-offs

CaseTimeSpaceWhy
ManacherO(n)O(n)Window right edge never moves left, so total expansion is at most n. 1,000 × a: 1,999 comparisons; a random 1,000-letter string over {a, b}: 3,991.
Expand around each centreO(n²) worstO(1)Same two strings: 500,500 comparisons on all-a, 5,086 on the random one.
Dynamic programming tableO(n²)O(n²)Fills n² = 1,000,000 cells for 1,000 characters; also answers any “is s[i..j] a palindrome?” in O(1) afterwards.
Hashing + binary search on lengthO(n log n)O(n)Compare a forward and a reverse rolling hash; probabilistic (hash collisions), but short to write.
Suffix tree / suffix array of s + reversed sO(n) to O(n log n)O(n)Heavy machinery for a problem Manacher solves with one array.

The ratio is the story. On all-a, centre expansion does 500,500 comparisons against Manacher’s 1,999, a factor of about 250; on a random string the two are within a small factor because palindromes there are short. Manacher’s guarantee is about the worst case, not the typical one. The price is code: the mirror, the cap and the window update are three places to get an index wrong, and on short inputs the quadratic version is shorter and just as fast in practice.

Common mistakes

  • Skipping the separators

    Without # every centre is a character, so even-length palindromes have no centre. On cbbd the odd-only version answers "c" where the right answer is "bb". Padding is what turns two cases into one.

  • Dropping the min() cap

    Writing P[i] = P[mirror] inside the window trusts a radius that may reach outside it. On babaaa that returns a longest palindrome of length 5, but the true answer is bab (length 3). Always cap at R − i.

  • Expecting one unique answer

    babad has two longest palindromes, bab and aba. Scanning for the maximum radius with > keeps the first (bab); >= keeps the last (aba). Both are correct, but a test that compares to one fixed string will fail on the other. Check the problem statement for a tie rule, and test by length plus a palindrome check.

  • Mapping back with the wrong formula

    The substring starts at (centre − radius) / 2 in the original. Using centre // 2 instead returns "ab" for abaab, where the right answer is "baab".

  • Never moving the window

    If C and R are not updated when a palindrome passes R, the answers are still right but the mirror stops helping and the algorithm quietly becomes quadratic: on 200 × a it makes 40,000 comparisons instead of 399.

Where this shows up

  • Longest palindromic substring

    The standard interview problem and the standard answer. Interviews usually accept the expand-around-centre solution and then ask for the linear one.

  • Counting palindromic substrings

    Each centre contributes ⌈P[i] / 2⌉ palindromes, so one pass counts them all. For abaab the sum is 8, which a brute-force check over all substrings confirms.

  • Shortest palindrome by prepending

    The longest palindromic prefix is the centre whose radius reaches the left end. For aacecaaa that prefix has length 7, so reversing the rest and prepending it gives aaacecaaa.

  • Palindrome partitioning and text analysis

    After one pass, “is s[i..j] a palindrome?” is a constant-time check on the radii, which replaces the quadratic table in partition-into-palindromes dynamic programs. It is the palindrome analogue of the Z-algorithm and KMP prefix function: reuse what you already learned about the string.

SOLVE IT YOURSELF

Solve it: longest palindrome in linear time

Expanding around every centre is O(n²). Manacher’s algorithm reuses the mirror of every palindrome it has already found and gets to O(n). Python or TypeScript, running for real in your browser.

YOUR TASK

Implement longest_palindrome(s): return the longest palindromic substring. Handle even-length palindromes ("cbbd" → "bb") and the empty string.

HINTS — 6 IDEAS
  1. First kill the odd/even split: interleave a separator, so "cbbd" becomes "#c#b#b#d#". Every palindrome in the transformed string has odd length, so one loop handles both cases.
  2. Track a window: center and its right reach — the palindrome extending furthest right so far.
  3. Inside that window, the mirror position 2·center − i already knows an answer: start from min(right − i, p[mirror]).
  4. The min is the crux — trust the mirror only up to the window edge; past it nothing has been compared.
  5. Then expand outward normally, and if you passed right, recentre the window on i.
  6. Mapping back: p[i] in the transformed string is exactly the palindrome’s length in the original, starting at (i − p[i]) // 2.
CPython · WebAssembly

Questions

Manacher vs expand-around-center?

Expand-around-center tries all ~2n centers and expands each independently, giving O(n²). Manacher keeps the same expansion but reuses the mirror radius inside the rightmost palindrome, so most centers start from a known radius and only genuine new matches cost work — O(n) overall.

How does it relate to the Z-algorithm and KMP?

All three are linear-time string tools built on a cached window and a mirror or failure function. The Z-algorithm measures prefix-match lengths, KMP tracks the longest prefix that is also a suffix, and Manacher measures palindrome radii. The window-reuse idea is shared.

How do I get the actual substring back?

In the padded string, P[i] is exactly the palindrome length in the original, and it starts at index (i − P[i]) / 2. Take the center with the largest P[i] and slice the original there.

The palindrome twin of the Z-algorithm.

Pad with separators, mirror the radii the window already knows, expand only past its edge — the longest palindrome falls out in one linear pass.

Finished this one? 0 / 99 Algorithms done
NextOne Pass, Every Word: Aho-Corasick Next on the “Matching without backing up” ladder · rung 5 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms