SDE & MLE Prep

5. Longest Palindromic Substring

Problem

Return the longest substring of s that is a palindrome (any one of them if there are ties).

Example: "babad" → "bab" (or "aba"); "cbbd" → "bb"

Constraints: length ≤ 1000.

Every palindrome has a centre (a char or a gap between chars: 2n−1 centres). Expand outward from each while ends match; keep the longest.

b a b a d
  ^          centre 'a' -> "bab"(1..3)  -> expand fails at d

Complexity: O(n²) time, O(1) space (Manacher's is O(n)).

class Solution:
    def longestPalindrome(self, s: str) -> str:
        best = (0, 0)
        for c in range(2 * len(s) - 1):
            l, r = c // 2, (c + 1) // 2
            while l >= 0 and r < len(s) and s[l] == s[r]:
                l, r = l - 1, r + 1
            if r - l - 1 > best[1] - best[0]:
                best = (l + 1, r)
        return s[best[0]:best[1]]