Longest Palindromic Substring
Given a string s, return the longest palindromic substring in s.
- 1 <= s.length <= 1000
- s consists of digits and English letters
s = "babad""bab"s = "cbbd""bb"s = "a""a"Finding the longest palindromic substring is a search for the widest mirrored symmetry within a string. The complexity of our solution depends on how much "memory" we use to avoid redundant checks.
The most naive way is to check every possible substring. With N² substrings and an O(N) check for each, this is too slow for large inputs.
# Check every i, j pair (N^2), then check if palindrome (O(N))
for i in range(len(s)):
for j in range(i, len(s)):
sub = s[i : j+1]
if sub == sub[::-1]:
# update max...We can avoid the O(N) check by noticing that "aba" is a palindrome ONLY IF its outer characters match ('a' == 'a') AND its inner substring ("b") is also a palindrome. We can store these boolean results in a 2D table to build longer palindromes from earlier, smaller results.
This is the "gold standard" for interviews. Instead of building a table, we recognize that every palindrome radiates outward from a central point.
Odd vs. Even Symmetry:
- A palindrome can have an Odd Soul (centered on a single character like "aba").
- A palindrome can have an Even Soul (centered between two characters like "abba").
Because of this, we must test 2N - 1 potential centers: every character in the string, and every gap between characters. For each center, we use two pointers (L and R) and expand outward as long as the characters match.
def longestPalindrome(s):
res = ""
for i in range(len(s)):
# 1. Expand from character (Odd: "aBa")
p1 = expand(s, i, i)
# 2. Expand from gap (Even: "aBBa")
p2 = expand(s, i, i + 1)
# Keep track of the longest one we've found
res = max(res, p1, p2, key=len)
return res
def expand(s, l, r):
# Move pointers outward while characters match
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
# Return the valid palindrome found (slices are non-inclusive at the end)
return s[l + 1 : r]The ultimate optimization. It uses the symmetry of previously found palindromes to "guess" the length of future ones, skipping almost all redundant expansions. While powerful, its complexity makes it a specialized tool rather than a standard interview requirement.
Bilateral Spectrum
Ready to find the longest palindrome by expanding from centers.