We want to find the longest palindromic substring within a given string s.
A palindrome is symmetric around its center, so the key idea is to expand around every possible center.
There are two types of palindrome centers:
- Odd-length: center at a single character (
center, center) - Even-length: center between two characters (
center, center + 1)
By expanding around all 2n − 1 possible centers, we can detect every palindrome found in the string.
- For each index
center, check two possibilities:checkPalin(s, center, center)→ odd-length palindromecheckPalin(s, center, center + 1)→ even-length palindrome
- Expansion continues while:
left >= 0right < ns[left] == s[right]
- After expanding, compute the palindrome length:
- Update
startandmax_lenif this palindrome is the longest so far.
- Update
- Each expansion is O(n), and we attempt
2ncenters, leading to overall O(n²) time.
A palindrome grows outward from its center.
Instead of checking all substrings (which would be O(n³)), we only expand from valid centers and stop as soon as the symmetry breaks.
Think of it as stretching a rubber band equally left and right from a center —
as long as both sides match, the palindrome grows.
- Time:
O(n²)— checking all centers with outward expansion - Space:
O(1)— only constant extra variables are used