Longest Palindromic Substring
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #5
Return the longest palindromic substring of s. If several have the maximum length, any of them is accepted (the tests list them).
Examples
text
"babad" → "bab" (or "aba")
"cbbd" → "bb"Hints
- Every palindrome has a center: a single character (odd length) or a gap between two characters (even length).
- There are
2n − 1centers. Expand outward from each while the ends match.
Approach
Expand around center: for each center, expand l--, r++ while s[l] == s[r], and track the longest result. That's O(n²) time and O(1) space. It's simpler and faster in practice than the O(n²)-space DP table dp[i][j] = s[i]==s[j] and dp[i+1][j−1].
Manacher's algorithm solves it in O(n) by reusing mirror information inside the current rightmost palindrome. It's worth naming in an interview, though rarely required.
Complexity
Time: O(n²). Space: O(1).
Python solution
def longestPalindrome(s):
best_l, best_r = 0, 0
for c in range(2 * len(s) - 1):
l, r = c // 2, c // 2 + c % 2
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
if r - l - 1 > best_r - best_l:
best_l, best_r = l + 1, r
return s[best_l:best_r]JavaScript solution
function longestPalindrome(s) {
let bl = 0, br = 0;
for (let c = 0; c < 2 * s.length - 1; c++) {
let l = c >> 1, r = l + (c & 1);
while (l >= 0 && r < s.length && s[l] === s[r]) { l--; r++; }
if (r - l - 1 > br - bl) { bl = l + 1; br = r; }
}
return s.slice(bl, br);
}