Find the longest stretch that reads the same both ways. Every palindrome mirrors around a center, a letter or a gap, so try all 2n−1 centers and grow outwards while the ends match, in O(n²) time and O(1) space.
▼The problem
LeetCode 5 (Medium). Given a string s, return its longest palindromic substring (a contiguous stretch that reads the same forwards and backwards).
Examples (LeetCode's): "babad" → "bab" ("aba" is also accepted) and "cbbd" → "bb", shown in capitals.
The solution
def longestPalindrome(s):
best = ""
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 > len(best):
best = s[l + 1:r]
return bestTranscript
Longest Palindromic Substring. Given a string, find its longest palindrome: a run of letters that reads the same forwards and backwards. In L, E, V, E, L, S, that's level, five letters long.
In B, A, B, A, D, the answer is B A B, though A B A ties it. In C, B, B, D, it's the double B.
The slow way checks every substring: about n squared of them, fifteen for B A B A D, and up to n steps to check each one. That's order n cubed.
Here's the trick. Picture a butterfly: every palindrome mirrors around its center. A center sits on a letter for odd lengths, or on a gap for even ones: two n minus one centers in all.
From each center, open the wings while the letters on both sides match. Stop at a mismatch or the end, and keep the widest.
In code, loop over the centers. Left and right start there, and while they're in bounds and their letters match, step outward. If the span inside beats the best, keep it.
Walk B A B A D. The first B is one letter, and the gap after it fails: B and A differ. Centered on the A, the two B's match: B A B, length three, a new best. Centered on the middle B, the A's match: A B A, also three, but not longer, so B A B stays. Every later center is shorter.
C B B D needs a gap. Between the two B's, they match: B B, length two. Then C and D differ. Letter centers alone would miss it.
Each of the two n minus one centers expands at most n steps: order n squared time, and constant space. A table of every substring takes the same time, but n squared space.
Pick a center, open the wings, keep the widest. That's Longest Palindromic Substring.