Practice › Dynamic Programming
Count Palindromic Substrings
Medium · Dynamic Programming · Asked at Meta, Amazon, Microsoft, LinkedIn
Print the number of substrings of s that are palindromes. Substrings at different positions count separately, even if they are equal.
Input
A single line with the string s.
Output
The number of palindromic substrings.
Constraints
- 1 ≤ |s| ≤ 1000
- only lowercase letters
Every palindrome has a centre — a character or the gap between two characters, 2n − 1 centres in all. Expand outwards from each centre while the two ends match, counting one palindrome per step.
Example 1
Input
abc
Output
3
Example 2
Input
aaa
Output
6
Hints
- Every palindrome is centred on a character (odd length) or between two characters (even length).
- There are 2n − 1 possible centres.
- Expand from each centre while both ends match — each step is one more palindrome.
Approach
For each centre, start i and j at the centre (j = i + 1 for even centres) and expand while s[i] = s[j], counting one palindrome per successful step. Every palindromic substring is found exactly once, from its own centre. The worst case (all letters equal) is O(n²), which is fine for n ≤ 1000.
Complexity: O(n²) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
long long count = 0;
for (int c = 0; c < 2 * n - 1; c++) {
int i = c / 2, j = i + c % 2;
while (i >= 0 && j < n && s[i] == s[j]) {
count++;
i--;
j++;
}
}
cout << count << "\n";
return 0;
}Python solution
s = input().strip()
n = len(s)
count = 0
for c in range(2 * n - 1):
i, j = c // 2, c // 2 + c % 2
while i >= 0 and j < n and s[i] == s[j]:
count += 1
i -= 1
j += 1
print(count)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int n = s.length();
long count = 0;
for (int c = 0; c < 2 * n - 1; c++) {
int i = c / 2, j = i + c % 2;
while (i >= 0 && j < n && s.charAt(i) == s.charAt(j)) {
count++;
i--;
j++;
}
}
System.out.println(count);
}
}Solve Count Palindromic Substrings online · All practice problems