Palindromic Substrings – Solution & Complexity
1. Understand What Counts
- Every substring that reads the same forwards and backwards counts, including all single characters.
- Substrings at different positions are counted separately even if they look identical.
- A brute-force check of every substring is
O(n^3); we can do much better by growing palindromes from their centers.
2. Expand Around Each Center
- A palindrome is defined by its center. A string of length
nhas2n - 1possible centers:nsingle-character centers (odd-length palindromes) andn - 1between-character centers (even-length palindromes). - From a center, expand outward while the characters on both sides match. Each successful expansion is one more palindromic substring.
3. Sum Odd and Even Centers
- For each index
i, count odd-length palindromes centered ati(expand(i, i)) and even-length palindromes centered betweeniandi + 1(expand(i, i + 1)). - Add the two counts for every index.
4. Final Complete Solution
- Expanding around every center visits each of the
2n - 1centers and expands at mostO(n)times, givingO(n^2)time. - Only a few counters are used, so the extra space is
O(1).