Return a longest contiguous piece of a string that reads identically forward and backward.
Problem
Input. A Python string text.
Output. Return a longest palindromic substring, not merely its length.
Rules. The selected characters must be contiguous; skipping intervening characters is not allowed.
Use exact code-point equality, without case conversion, Unicode normalization, or grapheme grouping.
Any longest palindrome is valid; the reference retains its first equal-length answer.
Leave the string unchanged. Empty input returns "".
Example. "babad" permits "bab" or "aba"; the reference returns "bab".
For "cbbd", return "bb".
Picture
An odd palindrome has a character center. An even palindrome has a gap center:
| Text | Center | Accepted inclusive ranges | Stop |
|---|---|---|---|
babad | Character one | [1,1] is a, then [0,2] is bab | Next radius exceeds bounds |
babad | Character two | [2,2] is b, then [1,3] is aba | Next endpoints b and d differ |
cbbd | Gap between one and two | [1,2] is bb | Outer c and d differ |
Every nonempty palindromic range has exactly one midpoint and radius. Trying both center types therefore covers every answer. Matching endpoints extend an already-palindromic inner range. A singleton or empty gap supplies the first inner case. On mismatch, every larger radius still contains that unequal pair. Bounds failure also forbids any larger range at that center.
middle selects a center. left and right are inclusive candidate endpoints.
The while guard certifies the current candidate before saving it. Moving outward creates an unchecked candidate, not another proven palindrome.
best_left and best_right retain the longest accepted range across completed centers.
The code compares right-left, which is length minus one. Strict > saves bab and keeps it when aba ties.
In the visual, m marks the center and aL/aR mark accepted odd endpoints.
The underline preserves the best half-open range. Final bL/bR mark the saved return range, not the last center’s d.
Problem trace
Separate level/aba comparison: a shorter later result cannot replace the best
Reference drawing
Problem trace
A center replaces the saved palindrome only when it finds a longer one
Execution trace
- m
- 0
- input
- babad
- best range
- [0,1) = b
- aL
- not shown→0
- calls
- not shown→expand(0,0); expand(0,1)
- accepted odd
- not shown→[0,1)
- aR
- not shown→2
- m
- 0→1
- calls
- expand(0,0); expand(0,1)→expand(1,1); expand(1,2)
- aL
- 0→1
- aR
- 2→3
- m
- 1→2
- aL
- 1→3
- m
- 2→3
- aR
- 3→not shown
- bL
- 3→0
- bR
- not shown→2
- m
- 3→4
- Recognize it
- The answer is a contiguous palindrome, whose symmetry guarantees one unique odd character center or even gap center.
- Keep true
- A successful guard certifies text[left:right+1] before updates. After the pointers move, the next candidate is untested. After each center, the saved range is a longest accepted range so far.
- Reuse it
- When validity is symmetric around a center, enumerate both center types and expand until the invariant breaks; change only the aggregation to find a longest value, count all values, or validate radii.
Code
def longest_palindrome(text: str) -> str:
best_left = best_right = 0
def expand(left: int, right: int) -> None:
nonlocal best_left, best_right
while left >= 0 and right < len(text) and text[left] == text[right]:
if right - left > best_right - best_left:
best_left, best_right = left, right
left -= 1
right += 1
for middle in range(len(text)):
expand(middle, middle)
expand(middle, middle + 1)
return text[best_left : best_right + 1]
Cost: worst-case comparisons and auxiliary pointer/count slots.
The returned slice allocates space for answer length .
On empty input, slicing returns ""; initialized [0,0] does not imply an existing character.
Change the Saved Result or the Workload
Start from longest_palindrome. Change either tie retention or the need to answer many range queries.
-
Keep every longest occurrence.
New task: Return all maximum-length half-open ranges, not only the first copied text.
Picture and change: Reset saved ranges on a longer candidate. Append on an equal length; unique centers prevent duplicate ranges.
Code: Complete replacement:
def longest_palindrome_ranges(text): ranges, best_length = [], 0 for middle in range(len(text)): for left, right in ((middle, middle), (middle, middle + 1)): while left >= 0 and right < len(text) and text[left] == text[right]: length = right - left + 1 if length > best_length: ranges, best_length = [[left, right + 1]], length elif length == best_length: ranges.append([left, right + 1]) left -= 1 right += 1 return sorted(ranges)Check:
babadreturns[[0,3],[1,4]];cbbdreturns[[1,3]]. Empty input returns[].Use when: Tied occurrence witnesses matter. Saved candidates require up to ranges; sorting final ties adds work.
-
Answer many interval queries.
New task: Decide whether each supplied half-open range is palindromic.
Picture and change: Store answers for inner intervals instead of discarding them after expansion. Descending
leftsolves rowleft+1first. Equal endpoints extend its inner answer; lengths one and two need no lookup.Code: Complete replacement. Queries must satisfy
0 <= left <= end <= len(text):def palindrome_queries(text, ranges): size = len(text) table = [[False] * size for _ in range(size)] for left in range(size - 1, -1, -1): for right in range(left, size): table[left][right] = text[left] == text[right] and ( right - left < 2 or table[left + 1][right - 1] ) return [True if left == end else table[left][end - 1] for left, end in ranges]Check:
babadwith[[0,3],[1,4],[0,5],[2,2]]gives[True,True,False,True]. Empty ranges are palindromic here.Use when: Repeated decisions justify preprocessing and table storage, then per query, plus returned answers.
Rebuild the Aggregation
What changes when the task asks for all palindrome occurrences?
Answer: Keep the same center enumeration. Add one for each accepted radius instead of retaining only a longest range.