Skip to content

Fix Manacher's algorithm returning a non-longest palindrome - #15789

Open
NightSeclude wants to merge 1 commit into
TheAlgorithms:masterfrom
NightSeclude:fix-manacher-even-palindromes
Open

NightSeclude wants to merge 1 commit into
TheAlgorithms:masterfrom
NightSeclude:fix-manacher-even-palindromes

Conversation

@NightSeclude

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

The bug

strings/manacher.py claims to find the longest palindromic substring, but it returns a shorter one whenever the true answer has even length:

>>> palindromic_string('abb')
'b'        # expected 'bb'
>>> palindromic_string('caccaaac')
'acca'     # expected 'caaac'
>>> palindromic_string('abcbbaab')
'bcb'      # expected 'baab'
>>> palindromic_string('cbbab')
'bb'       # expected 'bab'
>>> palindromic_string('')
IndexError # expected ''

The existing doctests only use inputs whose longest palindrome is odd-length, which is why the defect went unnoticed.

Root cause

length[j] stores the palindrome length in the separator-expanded string ('a|b|b'), and the code keeps the first center that maximizes it (if max_length < length[j]). Transformed length does not determine original length: for center j and radius k the span [j-k+1, j+k-1] covers only the even indices, so the original length is (2*k-1)//2 for an odd center and (2*k-1)//2 + 1 for an even one. For 'abb' the centers j=2 ('b', original length 1) and j=3 ('|', original length 2) both get transformed length 3; the strict < keeps j=2, so the shorter palindrome wins.

The fix

Track the best palindrome in the coordinates of the original string — compute the first and last even indices of each center's span, derive the original length from them, and slice input_string directly. The linear-time inner loop is untouched. An early return "" handles the empty input that used to raise IndexError, and doctests for the even-length and mixed cases above were added.

Verification

  • python strings/manacher.py (doctests): passes.
  • ruff check / ruff format --check: clean.
  • pytest tests/: 494 passed.
  • Exhaustive comparison against a brute-force oracle on 20 000 random strings over a 4-letter alphabet (lengths 0-14): 0 mismatches in length or content.

palindromic_string tracked the best palindrome by its length in the
separator-expanded string, where an odd-centered palindrome of length L
and an even-centered one of length L + 1 collide on the same value.
The strict '<' comparison then kept whichever came first, so inputs such
as 'abb' returned 'b' instead of 'bb' and 'caccaaac' returned 'acca'
instead of 'caaac'.

Track the best palindrome in the coordinates of the original string
instead, and guard the empty input that previously raised IndexError.
Adds doctests for even-length and mixed cases.

Co-Authored-By: Claude Code <[email protected]>
@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant