Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python longest palindrome: expand around odd and even centers

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A palindromic substring reads the same forward and backward within a contiguous sequence of code points.

Download Python source kit

Operation contract

The label fixture tests both a single-character center and a gap between adjacent characters. It expands while the two sides match and retains the longest observed span. Equal-length ties keep the earlier discovered span, which is the leftmost for this center order. Empty input returns an empty string. The function does not reorder characters or solve a subsequence problem.

Failure and ownership boundary

The accepted length is capped at 128 code points. Combining marks and user-perceived grapheme clusters can require a different comparison/editing contract. Center expansion is simple but quadratic on repeated input; it is not the linear-time palindrome algorithm. Python Unicode normalization: equality is not visual identity, Python longest common subsequence: rolling-row DP and its limits and Python sliding window: longest span without repeated symbols cover related distinctions.

Working program

python
def longest_label_palindrome(text):
    if not isinstance(text, str) or len(text) > 128:
        raise ValueError("bounded label required")
    best_left = 0; best_right = 0
    for center in range(2 * len(text) - 1):
        left = center // 2; right = left + center % 2
        while left >= 0 and right < len(text) and text[left] == text[right]:
            if right + 1 - left > best_right - best_left:
                best_left, best_right = left, right + 1
            left -= 1; right += 1
    return text[best_left:best_right]

print(longest_label_palindrome("DELLEVELBOM"))
print(longest_label_palindrome("ABBA"))
print("empty:", repr(longest_label_palindrome("")))
print("leftmost tie:", longest_label_palindrome("ABACDC"))

Output

Output
LEVEL
ABBA
empty: ''
leftmost tie: ABA

Costs and limits

Worst-case center expansion costs O(n²) comparisons and O(1) working indexes. The returned slice allocates up to O(n) characters. Code-point equality is not automatically a grapheme or locale policy.

Common Mistakes

  • Even-length palindromes need gap centers.
  • Substring and subsequence outputs have different contracts.

Connected lessons

Python sliding window: longest span without repeated symbols, Python Unicode normalization: equality is not visual identity, Python longest common subsequence: rolling-row DP and its limits.

python
longest-palindrome
Storage details