Longest Palindrome
Learn how to find the longest palindromic substring in a given string efficiently using an expand-around-center approach, avoiding cubic time complexity.
In depth
The Longest Palindromic Substring problem involves identifying the longest sequence of characters within a given string that reads the same forwards and backward. An efficient solution is crucial for processing text data, as naive approaches can lead to cubic time complexity.
The Expand Around Center Approach
Instead of generating all possible substrings and checking each for palindrome property, which is inefficient, we can use an "expand around center" strategy. This method considers every possible center for a palindrome and expands outwards to find the longest palindrome centered there.
Handling Odd and Even Length Palindromes
Palindromes can have either odd or even lengths. For odd-length palindromes (like "aba"), the center is a single character. For even-length palindromes (like "abba"), the center is between two identical characters. The expand around center approach handles both by considering two types of centers for each character index `i`:
1. Single character center: `(i, i)` – This initializes an expansion for odd-length palindromes. 2. Two character center: `(i, i + 1)` – This initializes an expansion for even-length palindromes, assuming `s[i] == s[i+1]`.
Expansion Process
For each center type, we use two pointers, `l` (left) and `r` (right), initialized to the center(s). We then expand these pointers outwards, decrementing `l` and incrementing `r`, as long as `l` is within bounds, `r` is within bounds, and the characters `s[l]` and `s[r]` are equal. With each successful expansion, we check if the current palindrome (`s[l...r]`) is longer than the longest palindrome found so far. If it is, we update our result.
function longest_palindrome(s):
longest_pal = ""
for i from 0 to length(s) - 1:
// Odd length palindromes
expand_and_update(s, i, i, longest_pal)
// Even length palindromes
expand_and_update(s, i, i + 1, longest_pal)
return longest_pal
function expand_and_update(s, l, r, longest_pal):
while l >= 0 AND r < length(s) AND s[l] == s[r]:
if (r - l + 1) > length(longest_pal):
longest_pal = substring(s, l, r + 1)
l = l - 1
r = r + 1Key takeaways
- The expand around center approach efficiently finds the longest palindromic substring.
- It avoids the cubic time complexity of checking all substrings.
- Both odd and even length palindromes are handled by considering two types of centers for each character.
- Pointers expand outwards from a center, checking for character equality.
- The result is updated whenever a longer palindrome is discovered.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →