To find the longest palindromic substring without using dynamic programming, we use a technique called center expansion. The idea is simple and intuitive: every palindrome is centered around a character (or between two characters), so we expand around each possible center and keep track of the longest one found.
Understanding Through Cases
Case 1: The palindrome has an odd length
Here, we consider each character as the center. For example, in the word racecar
, the character 'e' is at the center of the palindrome. We expand both left and right from this center and compare characters to check if it forms a palindrome.
Case 2: The palindrome has an even length
Some palindromes are centered between two characters, like abba
. In this case, we expand around the pair of equal characters and compare outward on both sides.
Case 3: Multiple palindromes
If there are multiple palindromic substrings of the same maximum length, we can return any one of them. For example, in babad
, both "bab" and "aba" are valid answers.
Case 4: No palindromes longer than 1
If the string contains no repeated characters or palindromes, like abc
, then each character is a palindrome of length 1. We can return any one of them.
Case 5: All characters are the same
In cases like aaaa
, the entire string is a palindrome. Expanding from any center will eventually cover the whole string.
Case 6: Empty string
If the input string is empty, we return an empty string as there’s no palindromic substring to be found.
Why This Works
By checking for palindromes centered at every character (and between characters), we cover all possibilities. The approach avoids building a 2D table (used in DP), and runs efficiently in O(n²) time and O(1) space, which is optimal for a non-DP solution.
It’s a powerful technique that gives the correct answer without any complex setup—just repeated expansion and comparison.