medium +20 pts

Longest Palindrome Substring

Find the longest palindromic substring in a given string.

Write a function `longest_palindrome(s: str) -> str` that takes a string `s` and returns the longest substring that is a palindrome. A palindrome is a string that reads the same forward and backward. If there are multiple palindromic substrings with the same maximum length, return the one that appears earliest (with the smallest starting index). The function should handle strings of length 0 to 1000. For an empty input string, return an empty string.

Constraints

0 <= len(s) <= 1000. The string contains only printable ASCII characters (no newlines). The time complexity should ideally be O(n^2) or better.

Example

>>> longest_palindrome('babad')
'bab'
>>> longest_palindrome('cbbd')
'bb'
>>> longest_palindrome('a')
'a'
>>> longest_palindrome('')
''
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider expanding around each character and between each pair of characters as a potential center.
Track the current best palindrome's start index and length as you scan.
For an empty string, return an empty string immediately.
When multiple palindromes tie for length, the earliest one is naturally selected if you only update when the length is strictly greater.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.