Palindromic Substrings
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #647
Count how many substrings of s are palindromes. Substrings at different positions count separately even if they're equal.
Examples
text
s = "abc" → 3 ("a", "b", "c")
s = "aaa" → 6 ("a" ×3, "aa" ×2, "aaa")
s = "abba" → 6 (a, b, b, a, bb, abba)Hints
- Interval DP:
pal[i][j] = s[i] == s[j] and pal[i+1][j−1], O(n²) time and space. - Every palindrome has a center: a character (odd length) or a gap between two characters (even length).
- Expand outward from each center while the ends match.
Approach
There are 2n − 1 centers: each index (odd-length palindromes) and each gap between neighbors (even-length). From each center, expand l left and r right while s[l] == s[r], counting one palindrome per successful expansion. O(n²) time, O(1) space.
The DP alternative fills pal[i][j] by increasing length using pal[i+1][j−1]. Manacher's algorithm solves it in O(n).
Complexity
Time: O(n²). Space: O(1).
Python solution
def countSubstrings(s):
n, count = len(s), 0
for center in range(2 * n - 1):
l, r = center // 2, center // 2 + center % 2
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
return countJavaScript solution
function countSubstrings(s) {
const n = s.length; let count = 0;
for (let center = 0; center < 2 * n - 1; center++) {
let l = center >> 1, r = l + (center % 2);
while (l >= 0 && r < n && s[l] === s[r]) { count++; l--; r++; }
}
return count;
}