Palindromic Substrings
Medium · Dynamic programming
Jump to codeCount all nonempty contiguous palindromic substrings. Substrings at different positions count separately even when their text is identical.
Examples
Example 1
s = "abc"
Output: 3
Example 2
s = "aaa"
Output: 6
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters.
Need a hint?
Every successful center expansion discovers one palindrome.
Asked in real interviews
Candidates reported versions of Palindromic Substrings from these company interviews. Some company questions are locked and open with Premium or XP.
- Count Palindromic Substrings by Expanding Around CentersVoleon
- Count all palindromic substringsReevo
- Count Palindromic SubstringsGoldman Sachs
Solution approach
Try every character as an odd center and every neighboring gap as an even center. While the endpoints match, increment the count and expand both ways. Each substring has one unique center, so nothing is counted twice.
Complexity
O(n²) time and O(1) space.
Python reference solution
def countSubstrings(s):
count = 0
for center in range(len(s)):
for left, right in ((center, center), (center, center + 1)):
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
JavaScript solution
function countSubstrings(s) {
let count = 0;
for (let center = 0; center < s.length; center++) {
for (let offset = 0; offset <= 1; offset++) {
let left = center, right = center + offset;
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++; left--; right++;
}
}
}
return count;
}
Java solution
import java.util.*;
class Solution {
public int countSubstrings(String s) {
int count = 0;
for (int center = 0; center < s.length(); center++) {
for (int offset = 0; offset <= 1; offset++) {
int left = center, right = center + offset;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
count++; left--; right++;
}
}
}
return count;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int count = 0;
for (int center = 0; center < (int)s.size(); center++) {
for (int offset = 0; offset <= 1; offset++) {
int left = center, right = center + offset;
while (left >= 0 && right < (int)s.size() && s[left] == s[right]) {
count++; left--; right++;
}
}
}
return count;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "abc" ]
3
[ "aaa" ]
6
[ "a" ]
1
[ "ab" ]
2
[ "abba" ]
6
Drafts are saved per language in this browser when storage is available.