3.8.9 · D3 · HinglishString Algorithms

Worked examplesPalindrome algorithms — Manacher's algorithm

2,595 words12 min read↑ Read in English

3.8.9 · D3 · Coding › String Algorithms › Palindrome algorithms — Manacher's algorithm

Matrix se pehle, vocabulary ka ek reminder taaki koi symbol anjaana na lage:

Agar inme se koi shaky lage, toh parent ki derivation dobara padho. Yeh page sirf unhi paanch cheezon ko assume karta hai.


Scenario matrix

Har input jo Manacher face kar sakta hai, inhi cells mein se ek mein aata hai. Neeche har worked example tagged hai un cell(s) ke saath jo woh exercise karta hai.

Cell Kya khaas hai Yeh alag case kyun hai
A. Odd champion longest palindrome ki odd length hai (aba) center ke ek real char pe padta hai
B. Even champion longest palindrome ki even length hai (abba) center ke ek # pe padta hai
C. All-same aaaa… mirror almost sab kuch predict karta hai; expansion rarely fire hoti hai — stress test
D. No repeats har char alag (abcd) har ; degenerate, reuse karne ko kuch nahi
E. Mirror strictly inside (Case A) exactly copy karo, expand mat karo
F. Mirror hits wall (Case B) cap copy karo, ke aage expand karna zaroori hai
G. (outside) fresh center, koi info nahi se shuru karo, scratch se expand karo
H. Boundary / single char "", "a" degenerate limits; bounds checks matter karte hain
I. Index mapping mein start recover karo //2 ka trap jo silently output corrupt karta hai
J. Counting total palindromic substrings har center pe use karta hai
K. Word-problem / exam twist applied phrasing prove karta hai ki tum ise use kar sakte ho, sirf run nahi

Neeche ke aath examples saare cells A–K hit karte hain.


Worked examples

Example 1 — Odd champion, outside-center start (Cells A, G)


Example 2 — Even champion, mirror hits the wall (Cells B, F)


Example 3 — Mirror strictly inside: woh speedup jo tum dekh sakte ho (Cell E)


Example 4 — All-same: stress test (Cell C)


Example 5 — No repeats: sab kuch degenerate (Cell D, H)


Example 6 — Index mapping: //2 ka trap (Cell I)


Example 7 — Saare palindromic substrings count karna (Cell J)


Example 8 — Word problem / exam twist (Cell K)


Recall Har trap kaun si cell mein rehta hai?

Even champion # pe center hota hai — kaun si cell? ::: Cell B "Mirror copy karo, expansion skip karo" — kaun si cell? ::: Cell E (mirror strictly inside) "Mirror bahut kam predict karta hai, wall ke aage expand karna zaroori hai" — kaun si cell? ::: Cell F s pe map back karte waqt //2 — kaun si cell? ::: Cell I aaaa… linearity stress-test — kaun si cell? ::: Cell C

Yeh bhi dekho: Expand Around Center ( baseline jo Manacher beat karta hai), Longest Palindromic Substring (headline application), Palindromic Tree (Eertree) (ek alternative structure), aur Amortized Analysis mein amortized-cost argument.