Problem
Return the longest palindromic substring of a string. If there are several of the same length, any one of them is accepted.
Original: LeetCode 5: Longest Palindromic Substring.
Examples
Example 1
`s = "babad"``"bab"`"aba" is also a valid answer.
Example 2
`s = "cbbd"``"bb"`Constraints
1 <= s.length <= 1000sconsist of only digits and English letters.
Hints
Hint 1
A substring is contiguous. A single character is a palindrome, so an answer always exists.
Hint 2
"Longest palindrome inside a string" is usually expand-around-center, or Manacher if you need linear time.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Check every substring and test whether it is a palindrome. That is O(n³) if you are not careful, or O(n²) if you stop early and reuse work.
Optimal. For each center, expand while s[L] == s[R]. There are 2n-1 centers: n odd centers and n-1 even centers between characters. Track the best start and length.
Alternative. Manacher's algorithm is O(n). A DP table dp[i][j] for "s[i..j] is a palindrome" is also O(n²) time and O(n²) space.
Complexity
- Time
- O(n²)
O(n²) time, O(1) extra space besides the output string.
- Space
- O(1)
Code
def longest_palindrome(s: str) -> str:
def expand(l: int, r: int) -> tuple[int, int]:
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return l + 1, r - 1
best_l = best_r = 0
for i in range(len(s)):
odd = expand(i, i)
even = expand(i, i + 1)
cur = odd if odd[1] - odd[0] >= even[1] - even[0] else even
if cur[1] - cur[0] > best_r - best_l:
best_l, best_r = cur
return s[best_l:best_r + 1]
if __name__ == "__main__":
assert longest_palindrome("babad") in {"bab", "aba"}
assert longest_palindrome("cbbd") == "bb"
print("ok")public class LongestPalindromicSubstring {
static String longestPalindrome(String s) {
int bestL = 0, bestR = 0;
for (int i = 0; i < s.length(); i++) {
int[] odd = expand(s, i, i);
int[] even = expand(s, i, i + 1);
int[] cur = odd[1] - odd[0] >= even[1] - even[0] ? odd : even;
if (cur[1] - cur[0] > bestR - bestL) {
bestL = cur[0];
bestR = cur[1];
}
}
return s.substring(bestL, bestR + 1);
}
static int[] expand(String s, int l, int r) {
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
return new int[] {l + 1, r - 1};
}
public static void main(String[] args) {
String a = longestPalindrome("babad");
if (!a.equals("bab") && !a.equals("aba")) throw new AssertionError(a);
if (!longestPalindrome("cbbd").equals("bb")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "babad" may return "bab" or "aba", and "cbbd" returns "bb".
- A string of identical characters is already a palindrome.
- Even-length palindromes are missed if you only expand around a single character.
Follow-ups
- Longest Palindromic Subsequence is a different problem: it allows deletions, so it becomes DP.
- Manacher's algorithm is the linear-time upgrade if the interviewer asks for it.
Interview script
"I treat every index as a center, and also every gap between two characters, and I expand while the ends match. There are a linear number of centers and each expansion is linear, so the time is quadratic, with constant extra space."
Sources (1)
- LeetCode 5: Longest Palindromic Substringleetcode.com