Longest Palindromic Substring – Solution & Complexity
1. Choose an Approach
- Checking every substring for being a palindrome is
O(n^3). - The clean, interview-friendly optimum is to expand around every possible center in
O(n^2)time andO(1)space. - A palindrome is fully described by its center, so we grow outward from each center and remember the longest match.
2. Expand Around a Center
- From a center, move two pointers outward while the characters match and stay in bounds.
- Return the start and end indices of the widest palindrome found for that center.
3. Track the Longest Over All Centers
- There are
2n - 1centers: one at each character (odd length) and one between each pair (even length). - For each center, expand and update the best
(start, end)window whenever a longer palindrome is found.
4. Final Complete Solution
- Each of the
2n - 1centers expands at mostO(n)times, so the total time isO(n^2). - We only store a couple of indices, so the extra space is
O(1).