Exercises — Palindrome algorithms — Manacher's algorithm
3.8.9 · D4· Coding › String Algorithms › Palindrome algorithms — Manacher's algorithm
Yeh page ek self-testing ladder hai. Har rung ek cognitive level upar chadhti hai — pieces ko pehchanne se lekar amortized argument ko master karne tak. Har problem ka ek pura worked solution ek collapsible callout ke andar chhupa hua hai — pehle khud try karo, phir reveal karo.
Prerequisites parent note Manacher's algorithm mein hain, aur neighbours Expand Around Center, Longest Palindromic Substring, Amortized Analysis, Z-Algorithm, KMP failure function, aur Palindromic Tree (Eertree) mein hain.
Level 1 — Recognition
L1.1 — Transform banao
Problem. ke liye transformed string likho. Uski length kya hai? se kaunsa formula deta hai?
Recall Solution
Har gap aur dono ends pe # insert karo:
Us string mein 7 characters hain. Generally . Yahan , toh . ✓
kyun? real characters hain aur gaps hain (pehle, beech mein, baad mein), jo deta hai separators-plus-reals.
L1.2 — value padhna
Problem. (indices ) mein, center b par baitha hai. Haath se, . Original mein yeh kaunsa palindrome describe karta hai, aur kitna lamba hai?
Recall Solution
Index ke around radius , indices tak phaila hua hai, yani poora #a#b#a#. Spacers hataane se milta hai aba.
Recovery rule kehta hai ki original palindrome length directly ke barabar hoti hai, toh length . Substring hai ==aba==. ✓
Level 2 — Application
L2.1 — s = "aba" par full trace
Problem. par Manacher run karo. Table bharo: har ke liye mirror (agar ), initial , expansion ke baad value, aur koi update do.
Recall Solution
se start karo.
| init | after expand | update | |||
|---|---|---|---|---|---|
| 0 | # | — () | 0 | 0 | — |
| 1 | a | — () | 0 | 1 (t[0]=#=t[2]=#) |
|
| 2 | # | , | 0 | — | |
| 3 | b | — (, since ) | 0 | 3 (b, then #=#... a=a... #=#) |
|
| 4 | # | , | 0 | — | |
| 5 | a | , | 1 | — | |
| 6 | # | , | 0 | — |
Final . at → sabse lamba palindrome aba, length 3. ✓
par expansion kyun nahi? Mirror ka tha, aur (wall ke barabar). Hum lete hain; value wall ko touch karti hai toh principle mein hum expand karne ki koshish karte hain — lekin t[7] bounds se bahar hai, toh kuch nahi badlta. Yeh Case B hai jo string edge par harmlessly degenerate ho jaata hai.
L2.2 — Substring index recover karna
Problem. s = "abacabad" ke liye, maano maximum radius hai -index par. mein starting index aur substring length do.
Recall Solution
Mapping rule: start = (k - P[k]) // 2.
Length . Toh substring hai s[1:6].
s = "abacabad" ke liye, s[1:6] = "bacab", jo length 5 ka palindrome hai. ✓
kyun? , se double dense hai (har real char ka ek # neighbour hai). -index par left edge, -index ke aadhey ke corresponding hai — aur kyunki # se start hota hai, integer division exactly land karta hai.
Level 3 — Analysis
L3.1 — Sabhi palindromic substrings ginana
Problem. Is fact ka use karte hue ki par centered palindromic substrings ki count hai, s = "aaa" ke palindromic substrings ki total count karo.
Recall Solution
, indices . compute karo (symmetry se verify kar sakte ho): ... ruko, aaa fully palindromic hai. Chalao:
- (
a): tak expand karta hai, set karo. - (
#): mirror ; init ; expandt[1]=a=t[3]=a→ ; phirt[0]=#=t[4]=#→ ; set karo. - (
a): mirror ; init ; expandt[2]=#=t[4]=#→ 2,t[1]=a=t[5]=a→ 3,t[0]=#=t[6]=#→ 3; set karo. - (
#): mirror ; init ; bounds ke baad expand nahi ho sakta → 2. - (
a): mirror ; init → 1. - (
#): 0.
Toh . Ab sum karo:
aaa ke 6 palindromic substrings: teen single a, do aa, ek aaa → . ✓ Total = 6.
L3.2 — kyun, aur sirf mirror kyun nahi
Problem. Ek concrete aur index do jahan blindly P[i] = P[2C-i] set karna (koi cap nahi) ek aisa palindrome claim karega jo actually exist nahi karta. Ek sentence mein explain karo ki cap kyun fix karta hai.
Recall Solution
lo (from s="baab"). Maano (# at middle), , aur hum par pahunch rahe hain. Mirror . Agar lekin , toh yeh Case A hai (fit hota hai) — yeh poke-out case nahi hai.
Poke-out tab hota hai jab : mirror palindrome badi palindrome ke left edge se left past extend karta hai. Us edge ke baad koi symmetry guarantee nahi hai, toh copy karna aise characters ke matching ko assert karta hai jo humne kabhi verify nahi kiye.
Ek sentence: par cap karna symmetry sirf wall tak trust karta hai, phir actually characters compare karke kuch bhi extra earn karta hai. ✓
Level 4 — Synthesis
L4.1 — Amortized bound, scratch se
Problem. Prove karo ki ek puri run mein sab expand loops mein character comparisons ki total count at most (yani ki length) hai. Figure mein mechanism reference karo.

Recall Solution
Har iteration ke kaam ko do buckets mein split karo:
minstep hai: pure arithmetic, koi comparisons nahi. Ignore karo.- Expand loop ek character comparison per iteration karta hai. Yahan key baat yeh hai: initial
minke baad, par palindrome already (wall) tak pahunch chuka hota hai. Expand loop ke andar har successful comparison palindrome ke right edge ko tak push karta hai, aur phir humR = i + P[i]execute karte hain.
Figure dekho: red wall marker sirf right slide karta hai, kabhi left nahi. Har successful expand comparison ko exactly ek position (in ) aage badhata hai. Kyunki se start hota hai aur se kabhi exceed nahi kar sakta, poori run mein successful comparisons ki count hai.
Har expand loop at most ek failing comparison ke saath khatam hota hai (woh mismatch jo use rokta hai), aur centers hain, jo deta hai failing comparisons. Total comparisons . ✓ Yeh Amortized Analysis argument hai: individual centers bahut zyada expand kar sakte hain, lekin shared resource sirf total steps aage ja sakta hai.
L4.2 — Naive expand ke liye worst case design karo
Problem. Expand Around Center kuch inputs par mein run karta hai. Length ki strings ki aisi family construct karo jo ise force kare, aur naive (no-mirror) algorithm ke under s = \texttt{aaaa} () ke liye successful expand comparisons ki exact count compute karo.
Recall Solution
Worst case hai all-same string . Har center ek badi palindrome ka middle hai, toh expansion har center se bahut door tak jaata hai.
aaaa ke liye successful comparisons count karo (indices ) par, jahan naive expand har center ko independently try karta hai:
Symmetry se radii hain ( par middle # poore aaaa ko center karta hai).
Radii ka sum = naive expand ke under successful comparisons ki count (har expansion ek success hai):
Toh naive ke liye 16 successful comparisons karta hai. Generally → . Manacher, iske contrast mein, mirror values reuse karke total expansion se bound rakhta hai. ✓
Level 5 — Mastery
L5.1 — Z-Algorithm reflection se relate karo
Problem. Manacher aur Z-Algorithm dono rightmost window maintain karte hain aur reflection ke zariye previously computed values reuse karte hain. Z-algorithm mein analogous recurrence state karo aur naam lo ek structural difference jo reflect hoti hai.
Recall Solution
Z-algorithm mein hum window maintain karte hain = ek prefix se match karne wala rightmost segment. Uske andar position ke liye, mirror hai (window ke left start se offset), aur: Compare Manacher: , phir expand karo. Structural difference: Manacher center ke around reflect karta hai (mirror index , ek point reflection), kyunki palindromes ek point ke baare mein symmetric hote hain. Z-algorithm window ke start tak reflect karta hai (translation to ), kyunki prefix-matches ek fixed prefix ke against compare hote hain, mirror nahi. Dono same amortized idea hain: reused value ko wall tak trust karo, phir baaki earn karo. Related failure-function machinery KMP failure function mein milti hai aur palindrome-specific automaton Palindromic Tree (Eertree) mein. ✓
L5.2 — Longest palindromic substring, end to end
Problem. s = "forgeeksskeegfor" ke liye, pura pipeline apply karo: sabse lamba palindromic substring kya hai aur uski length kya hai? Dikhao ki kaunsa aur ise produce karta hai, aur start-index mapping verify karo.
Recall Solution
Obvious lamba palindrome hai geeksskeeg (length 10). Pipeline se confirm karte hain.
mein, yeh palindrome mein even-length hai, toh mein uska center ek # hai. Uska radius mein original length ke barabar hai, toh us center par .
Palindrome geeksskeeg -index 3 par start hota hai (f o r g..., g index 3 hai). Mapping: start = (k - P[k]) // 2. Humein chahiye (k - 10)//2 = 3, toh , yani . Woh -index do s characters ke beech ka # hai — true even center. ✓
Final answer: longest palindromic substring = ==geeksskeeg, length 10==. Yeh Longest Palindromic Substring se match karta hai via s[start:start+P[k]] = s[3:13]. ✓
Recall Self-check: paanch ek-line reveals
mein, kiske barabar hai? ::: t[i] par centered palindrome ki exact length ke, mein.
Sirf ki jagah kyun? ::: Kyunki symmetry sirf wall tak guaranteed hai; usse aage verify karna padta hai.
Woh ek quantity kaunsi hai jo algorithm ko banati hai? ::: Wall sirf rightward move karta hai, total steps se zyada nahi.
-index ko radius ke saath start-index mein map karo. ::: start = (k - P[k]) // 2.
# separators kyun insert karte hain? ::: Yeh har palindrome ko odd-length banate hain toh sirf ek case handle hota hai.