AlgoTales · Roadmap

Manacher's algorithm

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Manacher's algorithm finds every palindrome (a word that reads the same both ways, like "madam") inside a string in one single pass. It does this by reusing what it already learned about the mirror image of the current spot instead of re-checking letters.

Practical use cases

  • Web app: Longest palindrome in a word-game app. A puzzle site shows a letter grid and challenges players to find the longest palindrome hidden in a long text. Expanding around every position works but gets slow on long inputs. Mirror reuse finds the answer in one pass, so the "show solution" button answers instantly.
  • Web app: Username or promo-code generator that avoids palindromes. A signup form generates referral codes and wants to avoid codes that read the same both ways, because users mistype them. Checking one code is easy, but scanning a big bank of codes for palindrome parts is quicker with the single-pass method, so thousands of codes are filtered in one go.
  • Web app: Counting palindromic pieces in an assignment checker. A coding-practice website grades students on counting all palindromic substrings of a given text. The grader needs a fast reference answer for thousands of test strings. Manacher's method counts them in one pass per string, so students get their result straight after pressing submit.
  • System: DNA palindromes. In DNA, a section that reads as its own reverse partner marks places where enzymes cut. Scientists scan genomes for these spots, and the single-pass approach keeps the scan fast on millions of letters. Scans that would take hours with the naive approach finish in seconds, because each letter is compared only a couple of times.

The story: The Mirror at the Rangoli Corner

During Diwali, Mira and Zoya made a long line of rangoli dots and coloured them in patterns. Mrs. Sharma challenged them: "Find the longest stretch that looks the same from left and right, like a mirror." Such a stretch is a palindrome. The girls tried standing at each dot and spreading their arms outwards as long as both sides matched.

That worked, but for a very long line they kept re-checking the same dots. One problem: some palindromes have a dot in the middle and some, like "baab", have the middle between two dots. So Zoya placed a small marker # between every pair of dots, so that every palindrome now has a real dot at its centre. Easy to handle!

Then Mira noticed the magic: if you are standing inside a big palindrome you already measured, your position has a mirror twin on the other side of the big palindrome centre, and its measured reach tells how far you can reach too, until you bump the edge of the big palindrome. Only past that edge do you need to compare new dots. This reuse makes the whole line cost one pass: Manacher's algorithm.

How to spot this problem, and where you need it

You need the longest or all palindromic parts of a string, and expanding from every position makes the work grow too quickly as the text gets longer.

Signs you need it

  • The problem statement says "longest palindromic substring" or "count all palindromic substrings".
  • Your solution loops over each centre and expands outward comparing letters, and it slows down on strings of 100,000 characters.
  • Many centres end up re-checking the same letters that a nearby centre has already compared.

Where to use it in a project

  • A text-puzzle or coding-practice feature that checks palindromes on long user inputs.
  • A data-cleaning script that detects symmetrical codes or IDs hiding in a large uploaded file.
  • A bioinformatics step that locates reverse-symmetric DNA sections along a long genome.

The solution

Put a filler character between all letters so that even and odd palindromes look alike. Walk through the string keeping the palindrome that reaches furthest to the right. For a new position inside that palindrome, look at its mirror position on the left: its answer is already known, so you can start with a head start and only compare letters beyond the edge. Each letter is compared at most a couple of times.

Payoff: Before: about a billion comparisons for a 100,000-letter text with centre expansion. After: roughly 200,000 steps, finished in a blink.

Explain it like I am 8

Stand in front of a mirror in the middle of a long mirror hall. If you already know how far a friend standing on the other side can see in a pattern, you are standing in the mirrored place, so you can see the same distance, at least until you reach the mirror hall's wall. Only beyond the wall do you have to look again.

How it works, step by step

  1. Pad the word with # between letters and at both ends: "abaab" becomes "#a#b#a#a#b#". Now every palindrome has an actual centre.
  2. Make an array p; p[i] is how far the palindrome around centre i reaches on each side.
  3. Keep the rightmost palindrome seen so far: its centre c and right edge r.
  4. For a new centre i inside it (i < r), start with min(r - i, p[2*c - i]): the mirror twin's answer, trimmed to the edge.
  5. Keep expanding while the letters on both sides match; if the reach passes r, move c and r to this palindrome.
  6. The largest p[i] is the length of the longest palindrome in the original word; its start is (i - p[i]) / 2.

The code in four languages

PHP

<?php
// Manacher: longest palindromic substring in O(n).
function longestPalindrome(string $s): string {
    if ($s === "") return "";
    $t = "#" . implode("#", str_split($s)) . "#";    // pad so every palindrome has a centre
    $n = strlen($t);
    $p = array_fill(0, $n, 0);                       // p[i] = reach on each side of centre i
    $c = 0; $r = 0;                                  // rightmost palindrome: centre c, right edge r
    for ($i = 0; $i < $n; $i++) {
        if ($i < $r) $p[$i] = min($r - $i, $p[2 * $c - $i]);   // mirror twin's answer
        while ($i + $p[$i] + 1 < $n && $i - $p[$i] - 1 >= 0
               && $t[$i + $p[$i] + 1] === $t[$i - $p[$i] - 1]) $p[$i]++;
        if ($i + $p[$i] > $r) { $c = $i; $r = $i + $p[$i]; }
    }
    $best = 0;
    for ($i = 1; $i < $n; $i++) if ($p[$i] > $p[$best]) $best = $i;
    return substr($s, intdiv($best - $p[$best], 2), $p[$best]);
}
echo longestPalindrome("abaab"), "\n";              // baab
echo longestPalindrome("forgeeksskeegfor"), "\n";   // geeksskeeg
echo longestPalindrome("racecar"), "\n";            // racecar

JavaScript

// Manacher: longest palindromic substring in O(n).
function longestPalindrome(s) {
  if (s === "") return "";
  const t = "#" + [...s].join("#") + "#";          // pad so every palindrome has a centre
  const n = t.length;
  const p = new Array(n).fill(0);                  // p[i] = reach on each side of centre i
  let c = 0, r = 0;                                // rightmost palindrome: centre c, right edge r
  for (let i = 0; i < n; i++) {
    if (i < r) p[i] = Math.min(r - i, p[2 * c - i]);   // mirror twin's answer
    while (i + p[i] + 1 < n && i - p[i] - 1 >= 0
           && t[i + p[i] + 1] === t[i - p[i] - 1]) p[i]++;
    if (i + p[i] > r) { c = i; r = i + p[i]; }
  }
  let best = 0;
  for (let i = 1; i < n; i++) if (p[i] > p[best]) best = i;
  return s.substr((best - p[best]) / 2, p[best]);
}
console.log(longestPalindrome("abaab"));           // baab
console.log(longestPalindrome("forgeeksskeegfor")); // geeksskeeg
console.log(longestPalindrome("racecar"));         // racecar

Java

public class Main {
    // Manacher: longest palindromic substring in O(n).
    static String longestPalindrome(String s) {
        if (s.isEmpty()) return "";
        StringBuilder sb = new StringBuilder("#");       // pad so every palindrome has a centre
        for (char ch : s.toCharArray()) sb.append(ch).append('#');
        String t = sb.toString();
        int n = t.length();
        int[] p = new int[n];                            // p[i] = reach on each side of centre i
        int c = 0, r = 0;                                // rightmost palindrome: centre c, right edge r
        for (int i = 0; i < n; i++) {
            if (i < r) p[i] = Math.min(r - i, p[2 * c - i]);   // mirror twin's answer
            while (i + p[i] + 1 < n && i - p[i] - 1 >= 0
                   && t.charAt(i + p[i] + 1) == t.charAt(i - p[i] - 1)) p[i]++;
            if (i + p[i] > r) { c = i; r = i + p[i]; }
        }
        int best = 0;
        for (int i = 1; i < n; i++) if (p[i] > p[best]) best = i;
        int start = (best - p[best]) / 2;
        return s.substring(start, start + p[best]);
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("abaab"));              // baab
        System.out.println(longestPalindrome("forgeeksskeegfor"));   // geeksskeeg
        System.out.println(longestPalindrome("racecar"));            // racecar
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// longestPalindrome is Manacher's algorithm: longest palindromic substring in O(n).
func longestPalindrome(s string) string {
	if s == "" {
		return ""
	}
	t := "#" + strings.Join(strings.Split(s, ""), "#") + "#" // pad so every palindrome has a centre
	n := len(t)
	p := make([]int, n) // p[i] = reach on each side of centre i
	c, r := 0, 0        // rightmost palindrome: centre c, right edge r
	for i := 0; i < n; i++ {
		if i < r {
			p[i] = min(r-i, p[2*c-i]) // mirror twin's answer
		}
		for i+p[i]+1 < n && i-p[i]-1 >= 0 && t[i+p[i]+1] == t[i-p[i]-1] {
			p[i]++
		}
		if i+p[i] > r {
			c, r = i, i+p[i]
		}
	}
	best := 0
	for i := 1; i < n; i++ {
		if p[i] > p[best] {
			best = i
		}
	}
	start := (best - p[best]) / 2
	return s[start : start+p[best]]
}

func main() {
	fmt.Println(longestPalindrome("abaab"))            // baab
	fmt.Println(longestPalindrome("forgeeksskeegfor")) // geeksskeeg
	fmt.Println(longestPalindrome("racecar"))          // racecar
}

Time: O(n) · Extra space: O(n). The right edge r only moves forward, so all the expanding together costs about n steps. Checking every centre naively would cost O(n²).

Watch out for

  • Forgetting the # padding, so even-length palindromes like "baab" are missed.
  • Not trimming with min(r - i, p[mirror]): beyond the edge of the big palindrome the mirror is not trustworthy.
  • Mixing up radius in the padded string with the real start index. Start in the original = (centre - radius) / 2.

Quick check

  1. Why do we insert # between letters?
    • To make the string longer for speed
    • So even and odd palindromes both have a centre
    • To sort the letters
  2. Inside the known big palindrome, what gives a free head start?
    • The mirror twin position's radius (trimmed to the edge)
    • The first letter
    • The length of the word
  3. Time complexity of Manacher's algorithm?
    • O(n²)
    • O(n log n)
    • O(n)