PrepStack · Markdown HTML

Center expansion / Manacher palindrome

String matching, hashing, and palindrome · HTML

Formal shape

Odd centers are (i,i), even centers (i,i+1); expand while s[l]==s[r].

Recognition signals

False friends

SignalWhy it is different
Palindromic subsequenceA subsequence may skip characters, so center expansion misses answers; use DP.
Many interval-palindrome queriesRepeated expansion is costly; consider DP, hashing, or precomputed Manacher radii.

Core invariant

At loop entry s[l+1:r] is palindromic; equal new endpoints preserve symmetry.

State, transition, and processing order

ItemDefinition
StateCurrent endpoints, best interval, and optionally a palindrome counter.
TransitionExpand from every odd and even center; on success update the answer, then decrement l and increment r.
Frontier / orderThe two endpoints are a symmetric frontier; the first mismatch rules out every larger radius at that center.

Python skeleton

def palindromes_by_center(s):
    best = (0, 0)
    count = 0
    def grow(l, r):
        nonlocal best, count
        while l >= 0 and r < len(s) and s[l] == s[r]:
            count += 1
            if r-l > best[1]-best[0]: best = (l, r)
            l -= 1; r += 1
    for i in range(len(s)):
        grow(i, i)
        grow(i, i+1)
    l, r = best
    return s[l:r+1], count

Correctness sketch

  1. Every palindrome has one center and radius.
  2. The algorithm enumerates all 2n-1 odd/even centers.
  3. For one center it checks radii in order, and a mismatch forbids larger radii.
  4. Thus each palindrome is counted once and a longest one is recorded.

Complexity

TimeSpaceParameters
O(n²) worst caseO(1) excluding outputstring length n; Manacher reduces the bound to O(n)

Edge cases

Error patterns

PatternWhy it fails / fix
Only odd centersEvery even-length palindrome is missed.
Bounds checked after indexingValidate endpoints before reading characters.
Confusing radius and lengthOdd and even formulas differ; storing endpoints avoids ambiguity.

Selection and exclusion rules

RelationTemplateBoundary
query alternativeRolling hash / Rabin-KarpMany specified ranges must be checked quickly

Original micro-example

PartDetail
ResultThe longest palindrome is aba, and there are five palindromic substrings.
ScenarioString abac.
WalkthroughCenter b grows to aba; four single characters contribute four more, while other expansions stop immediately.

Recall prompts

My notes