Longest palindromic substring
Expand around every centre. A palindrome is symmetric about its middle, so try each possible middle and grow outwards while the characters match. There are 2n − 1 centres, not n, because an even-length palindrome is centred between two characters. O(n²) time, O(1) space.
Overview
Why 2n − 1 centres
An odd-length palindrome like aba is centred on a character. An even-length one like abba is centred on the gap between two. So there are n character centres and n − 1 gap centres.
Forgetting the even case is the classic bug here: the code passes on racecar and fails on abba, which is exactly the sort of half-correct that survives a quick test.
Step through it
What to watch
- Each centre grows outwards until the characters stop matching.
- Odd and even centres are tried separately — that is the 2n−1.
- Nothing is allocated; only indices move.
Say this out loud
"Expand around centres. 2n-1 centres because even-length palindromes sit between characters. O(n²) time but O(1) space, which beats the DP table. There's an O(n) algorithm - Manacher's - but I'd only reach for it if you want it."