Palindromic Substrings
Medium
Topics
Given a string s, return the number of palindromic substrings in it. Substrings at different start or end positions count separately even if identical.
Example 1
Every single character is already a palindrome, so the count starts at 3 and grows from there to 3. Expanding from each of the 2n−1 centres counts each one exactly once, with no substring ever built or compared as a whole.
Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "abc" Output: 3 Explanation: The three single characters.
Example 2
Input: s = "aaa" Output: 6
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every palindrome has a center — either a single character (odd length) or a gap between two characters (even length). Expanding outward from each of the 2n-1 centers finds all palindromes without recomputation.
Approach
- For each index, expand around the odd center (i, i) and the even center (i, i+1).
- While the two ends match, count one palindrome and widen.
- Sum the counts over all centers.
Dry Run
s = "aaa". There are 2n - 1 = 5 centres, not 3.
centre 0 odd, both at index 0 finds "a" total 1
centre 1 even, gap between 0 and 1 finds "aa" total 2
centre 2 odd, both at index 1 finds "a", then "aaa" total 4
centre 3 even, gap between 1 and 2 finds "aa" total 5
centre 4 odd, both at index 2 finds "a" total 6
answer 6
Centre 2 is the one that earns its keep: it finds two palindromes, "a" and then
"aaa", because each successful expansion is itself a distinct substring and gets
counted on the way out. The count is incremented inside the while loop, not after
it.
The `left = center // 2` and `right = left + center % 2` pair is what folds both
parities into one loop. Even centres get right = left + 1, which starts the
expansion straddling a gap; odd centres get right = left, starting on a single
character.
Use only the n odd centres and every even-length palindrome is lost: "aaa" gives
4 instead of 6, missing both copies of "aa".Complexity
- Time — O(n^2): each of the ~2n centers can expand up to n times.
- Space — O(1): only pointers and a counter.
Common Pitfalls
- There are
2n - 1centres, notn. Every gap between two characters is a centre too, and skipping them loses every even-length palindrome:aaagives 4 instead of 6. left = center // 2andright = left + center % 2is the trick that folds both cases into one loop -- even centres getright = left + 1, odd centres getright = left.
Full Solution — all languages
class Solution:
def countSubstrings(self, s):
res=0
for center in range(2*len(s)-1):
left=center//2
right=left+center%2
while left>=0 and right<len(s) and s[left]==s[right]:
res+=1
left-=1
right+=1
return resimport java.util.*;
class Solution {
public int countSubstrings(String s) {
int res=0,n=s.length();
for(int center=0;center<2*n-1;center++) {
int left=center/2,right=left+center%2;
while(left>=0&&right<n&&s.charAt(left)==s.charAt(right)) {
res++;
left--;
right++;
}
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countSubstrings(string s) {
int res=0,n=s.size();
for(int center=0;center<2*n-1;center++) {
int left=center/2,right=left+center%2;
while(left>=0&&right<n&&s[left]==s[right]) {
res++;
left--;
right++;
}
}
return res;
}
};/**
* @param {string} s
* @return {number}
*/ var countSubstrings = function(s) {
let res=0;
for(let center=0;center<2*s.length-1;center++) {
let left=Math.floor(center/2),right=left+(center%2);
while(left>=0&&right<s.length&&s[left]===s[right]) {
res++;
left--;
right++;
}
}
return res;
};