15% off all plans & roadmaps Use code
See plansPalindromic Substrings
- LeetCode 647
- Medium
- Two Pointers
- Expanding From Center (Palindromes)
Updated
TL;DR: Count every contiguous substring of s that reads the same in both directions. Expand outward from each of the 2n - 1 possible centers, and count each match as you grow, for O(n^2) time and O(1) space.
Problem
Given a string s, return the number of palindromic substrings it contains.
A string is a palindrome if it reads the same forward and backward. A substring is a contiguous run of characters inside the string. Substrings at different positions count separately, even when their text is identical.
Example 1
Input: s = "abc" Output: 3 Explanation: The palindromic substrings are "a", "b" and "c".
Example 2
Input: s = "aaa" Output: 6 Explanation: The palindromic substrings are "a", "a", "a", "aa", "aa" and "aaa".
Constraints
1 <= s.length <= 1000sconsists of lowercase English letters.
Constraints that matter
s.lengthis at most 1000, so there are about 500,000 substrings. An O(n^2) algorithm does roughly a million steps, which is fast. An O(n^3) one does up to about 10^8 to 10^9 basic steps, which is risky.- The answer counts positions, not distinct strings. A set of seen palindromes gives the wrong total on inputs like
aaa. - The maximum answer is about n * (n + 1) / 2 = 500,500, which fits in a 32-bit int. No overflow handling is needed.
- Only lowercase letters appear, so there are no Unicode or case-folding concerns. Compare characters directly.
Hints
Hint 1
A palindrome is symmetric, so it has a center.
Hint 2
Try every substring and test each one on its own.
Solution
Intuition
A palindrome is symmetric, so it has a center. If s[l..r] is a palindrome, then s[l-1..r+1] is a palindrome exactly when s[l-1] == s[r+1]. The inside is already known to be good, so you only check the two new outer characters.
Picture folding a paper strip at a crease. The crease is the center, each matching pair of letters that lines up across the fold is one palindrome, and the first mismatch means that fold stops working.
That suggests growing palindromes from the inside out instead of testing substrings from scratch. This is the expanding-from-center form of two pointers. Put a left pointer and a right pointer on a center and move them apart while the characters match.
There are two kinds of center. An odd-length palindrome like aba has a character as its center. An even-length palindrome like abba has a gap between two characters as its center. A string of length n has n character centers and n - 1 gap centers, so 2n - 1 centers in total.
Every palindromic substring has exactly one center, so it is counted exactly once. Each successful step of an expansion is one new palindrome. The first mismatch ends that center for good, because any wider substring would contain the mismatched pair at its ends.
You can spot this pattern by the words substring and palindrome together with a limit near 1000. That limit hints at an O(n^2) answer, and symmetry hints that the center is the natural thing to iterate over.
Worked example
Input: s = "abccba" Output: 9 Explanation: Six single letters are palindromes. The three others are cc at indices 2-3, bccb at indices 1-4, and abccba at indices 0-5. All three share the same center between the two c's. No other substring of length 2 or more reads the same in both directions.
Approach 1: Brute force
Try every substring and test each one on its own. Two nested loops pick the start i and end j. A third loop walks two pointers inward from both ends to check the palindrome property.
This is correct and easy to write. It also wastes the most work, which the later approaches fix.
Steps
- Set
count = 0. - For each start index
ifrom 0 to n - 1, loop over each end indexjfromito n - 1. - Put a pointer
latiand a pointerratj. - While
l < r, compares[l]ands[r]. On a mismatch, mark the substring as not a palindrome and stop. - Otherwise move
lright andrleft. - If no mismatch was found, add 1 to
count. - Return
count.
Dry run
Take s = abccba. There are 21 substrings, and each is checked from its two ends.
- Length 1: all 6 pass at once because
l == r. Count is 6. - Length 2:
ab,bc,cb,bafail on the first compare.ccpasses. Count is 7. - Length 3:
abc,bcc,ccb,cbaall fail on the first compare. Count stays 7. - Length 4:
abccandccbafail.bccbcompares b with b, then c with c, and passes. Count is 8. - Length 5:
abccbandbccbafail on the first compare. Count stays 8. - Length 6:
abccbamatches a/a, b/b, c/c and passes. Count is 9.
The result is 9.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(1) |
Here n is the length of s. There are n * (n + 1) / 2 substrings, which is O(n^2). Checking one substring walks at most half its length, which is O(n), so the total is O(n^3). The code keeps only a few integers, so extra space is O(1).
PythonTested in our runner
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
count = 0
for i in range(n):
for j in range(i, n):
l, r = i, j
ok = True
while l < r:
if s[l] != s[r]:
ok = False
break
l += 1
r -= 1
if ok:
count += 1
return count
JavaTested in our runner
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int l = i, r = j;
boolean ok = true;
while (l < r) {
if (s.charAt(l) != s.charAt(r)) {
ok = false;
break;
}
l++;
r--;
}
if (ok) count++;
}
}
return count;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int l = i, r = j;
bool ok = true;
while (l < r) {
if (s[l] != s[r]) {
ok = false;
break;
}
l++;
r--;
}
if (ok) count++;
}
}
return count;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var countSubstrings = function(s) {
const n = s.length;
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let l = i, r = j;
let ok = true;
while (l < r) {
if (s[l] !== s[r]) {
ok = false;
break;
}
l++;
r--;
}
if (ok) count++;
}
}
return count;
};
GoTested in our runner
func countSubstrings(s string) int {
n := len(s)
count := 0
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
l, r := i, j
ok := true
for l < r {
if s[l] != s[r] {
ok = false
break
}
l++
r--
}
if ok {
count++
}
}
}
return count
}
C#Tested in our runner
public class Solution {
public int countSubstrings(string s) {
int n = s.Length;
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int l = i, r = j;
bool ok = true;
while (l < r) {
if (s[l] != s[r]) {
ok = false;
break;
}
l++;
r--;
}
if (ok) count++;
}
}
return count;
}
}
Approach 2: Dynamic programming table
What's slow: each substring check starts from scratch, even though s[i+1..j-1] was often tested already. That repeated O(n) walk is what pushes the cost to O(n^3).
The insight that fixes it: s[i..j] is a palindrome when s[i] == s[j] and the inside s[i+1..j-1] is a palindrome. Store that answer in a table dp[i][j]. Each cell then costs O(1) to fill from a cell you already computed.
The inside of a substring has a larger start index. So fill i from the end of the string down to 0, and j from i upward.
Steps
- Create an n by n boolean table
dp, all false, and setcount = 0. - Loop
ifrom n - 1 down to 0. - For each
i, loopjfromiup to n - 1. - If
s[i] == s[j]and eitherj - i < 2ordp[i+1][j-1]is true, setdp[i][j]to true. - Each time a cell becomes true, add 1 to
count. - Return
count.
Dry run
Take s = abccba (indices 0..5: a b c c b a). Rows are filled from i = 5 upward.
i = 5:dp[5][5]is true. Count 1.i = 4:dp[4][4]true.dp[4][5]is b vs a, false. Count 2.i = 3:dp[3][3]true.dp[3][4]is c vs b, false.dp[3][5]is c vs a, false. Count 3.i = 2:dp[2][2]true.dp[2][3]is c vs c withj - i = 1, true. Count 5.dp[2][4]anddp[2][5]fail on the ends.i = 1:dp[1][1]true.dp[1][4]is b vs b anddp[2][3]is true, so it is true. Count 7. Other cells in the row fail.i = 0:dp[0][0]true.dp[0][5]is a vs a anddp[1][4]is true, so it is true. Count 9.
The result is 9.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n^2) |
Here n is the length of s. The table has n * n cells and the loops visit about n * (n + 1) / 2 of them. Each cell is filled with one comparison and one table lookup, so the time is O(n^2). The table itself holds n * n booleans, so the space is O(n^2).
PythonTested in our runner
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
dp = [[False] * n for _ in range(n)]
count = 0
for i in range(n - 1, -1, -1):
for j in range(i, n):
# inside is empty, one char, or already known to be a palindrome
if s[i] == s[j] and (j - i < 2 or dp[i + 1][j - 1]):
dp[i][j] = True
count += 1
return count
JavaTested in our runner
class Solution {
public int countSubstrings(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
int count = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) {
dp[i][j] = true;
count++;
}
}
}
return count;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int count = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1])) {
dp[i][j] = true;
count++;
}
}
}
return count;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var countSubstrings = function(s) {
const n = s.length;
const dp = Array.from({ length: n }, () => new Array(n).fill(false));
let count = 0;
for (let i = n - 1; i >= 0; i--) {
for (let j = i; j < n; j++) {
if (s[i] === s[j] && (j - i < 2 || dp[i + 1][j - 1])) {
dp[i][j] = true;
count++;
}
}
}
return count;
};
GoTested in our runner
func countSubstrings(s string) int {
n := len(s)
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
count := 0
for i := n - 1; i >= 0; i-- {
for j := i; j < n; j++ {
if s[i] == s[j] && (j-i < 2 || dp[i+1][j-1]) {
dp[i][j] = true
count++
}
}
}
return count
}
C#Tested in our runner
public class Solution {
public int countSubstrings(string s) {
int n = s.Length;
bool[,] dp = new bool[n, n];
int count = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 2 || dp[i + 1, j - 1])) {
dp[i, j] = true;
count++;
}
}
}
return count;
}
}

Solution pattern
Expanding From Center (Palindromes)
Part of Two Pointers
Approach 3: Expand around each centerOptimalExpanding From Center (Palindromes)
What's slow: the table spends O(n^2) memory to remember answers for substrings that are not palindromes at all. Most cells are false and never help. You only need the palindromes, and each one is built from a smaller palindrome with the same center.
The insight that fixes it: iterate over the 2n - 1 centers and grow outward from each. Keep going while the two outer characters match, and count one palindrome per successful step. The first mismatch stops that center. Only two pointers and a counter are needed, so memory drops to O(1).
Steps
- Set
count = 0. - For each index
ifrom 0 to n - 1, run an expansion withl = iandr = i. This covers odd-length palindromes. - Run a second expansion with
l = iandr = i + 1. This covers even-length palindromes. - In an expansion, loop while
l >= 0,r < nands[l] == s[r]. - On each pass of the loop, add 1 to
count, then dol -= 1andr += 1. - When the loop ends, move to the next center.
- Return
count.
Dry run
Take s = abccba (indices 0..5: a b c c b a). Each row shows what the two expansions from index i find.
| i | Odd expansion (i, i) | Odd found | Even expansion (i, i+1) | Even found | Running count |
|---|---|---|---|---|---|
| 0 | a; then l = -1 stops | 1 | a vs b mismatch | 0 | 1 |
| 1 | b; then a vs c mismatch | 1 | b vs c mismatch | 0 | 2 |
| 2 | c; then b vs c mismatch | 1 | cc, then bccb, then abccba, then l = -1 stops | 3 | 6 |
| 3 | c; then c vs b mismatch | 1 | c vs b mismatch | 0 | 7 |
| 4 | b; then c vs a mismatch | 1 | b vs a mismatch | 0 | 8 |
| 5 | a; then r = 6 stops | 1 | r = 6 out of bounds | 0 | 9 |
The even center between indices 2 and 3 is the only one that grows past length 1. It yields all three palindromes of length 2 or more. The result is 9.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the length of s. There are 2n - 1 centers, and each expansion moves its pointers outward at most n / 2 steps before it hits a boundary. That gives at most (2n - 1) * n / 2, which is O(n^2). A string of one repeated letter reaches this bound, since the answer itself is n * (n + 1) / 2. Space is O(1) because only the pointers and the counter are stored.
PythonTested in our runner
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
def expand(l: int, r: int) -> int:
found = 0
# bounds are checked before indexing
while l >= 0 and r < n and s[l] == s[r]:
found += 1
l -= 1
r += 1
return found
count = 0
for i in range(n):
count += expand(i, i) # odd length, center is a character
count += expand(i, i + 1) # even length, center is a gap
return count
JavaTested in our runner
class Solution {
public int countSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += expand(s, i, i); // odd length
count += expand(s, i, i + 1); // even length
}
return count;
}
private int expand(String s, int l, int r) {
int found = 0;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
found++;
l--;
r++;
}
return found;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int count = 0;
int n = s.size();
for (int i = 0; i < n; i++) {
count += expand(s, i, i); // odd length
count += expand(s, i, i + 1); // even length
}
return count;
}
private:
int expand(const string& s, int l, int r) {
int found = 0;
int n = s.size();
while (l >= 0 && r < n && s[l] == s[r]) {
found++;
l--;
r++;
}
return found;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var countSubstrings = function(s) {
const n = s.length;
const expand = (l, r) => {
let found = 0;
while (l >= 0 && r < n && s[l] === s[r]) {
found++;
l--;
r++;
}
return found;
};
let count = 0;
for (let i = 0; i < n; i++) {
count += expand(i, i); // odd length
count += expand(i, i + 1); // even length
}
return count;
};
GoTested in our runner
func countSubstrings(s string) int {
count := 0
for i := 0; i < len(s); i++ {
count += expandCenter(s, i, i) // odd length
count += expandCenter(s, i, i+1) // even length
}
return count
}
func expandCenter(s string, l, r int) int {
found := 0
for l >= 0 && r < len(s) && s[l] == s[r] {
found++
l--
r++
}
return found
}
C#Tested in our runner
public class Solution {
public int countSubstrings(string s) {
int count = 0;
for (int i = 0; i < s.Length; i++) {
count += Expand(s, i, i); // odd length
count += Expand(s, i, i + 1); // even length
}
return count;
}
private int Expand(string s, int l, int r) {
int found = 0;
while (l >= 0 && r < s.Length && s[l] == s[r]) {
found++;
l--;
r++;
}
return found;
}
}
Common mistakes
- Only calling
expand(i, i). That finds odd-length palindromes only and missescc,bccbandabccbain the example. Add the second callexpand(i, i + 1)for even centers. - Writing the loop condition as
s[l] == s[r] && l >= 0 && r < n. The character access runs first and goes out of range at the edges. Checkl >= 0andr < nbefore touchings[l]ors[r]. - Storing palindromes in a set and returning its size. The problem counts positions, so
aaamust give 6, not 3. Count each successful expansion step and keep no strings. - Stopping the whole scan at the first non-palindrome in the brute force or the DP. A bad pair only kills that substring, not shorter or later ones. Break out of the inner check loop only, and keep iterating over
iandj. - Filling the DP table with
igoing upward. Thendp[i+1][j-1]has not been computed yet and reads false. Loopifrom n - 1 down to 0 so the inner cell is ready. - Forgetting the
j - i < 2base case in the DP. Forj = i + 1the inside index range is empty anddp[i+1][j-1]reads the wrong cell. Treat lengths 1 and 2 as true whenever the end characters match.
Edge cases
s = a(length 1): the answer is 1. The odd expansion finds the single letter and the even expansion goes out of bounds at once.s = aaaa...awith 1000 letters: this is the worst case, with answer 500,500. It still fits in anintand runs in about a million steps with center expansion.s = ab(no repeats): the answer is 2. Only single letters count, and the even center fails on the first compare.s = aa: the answer is 3, which is two single letters plusaa. This checks the even-center case with the smallest input.s = abcd...z(all distinct letters): the answer equals the length, since only single letters are palindromes.s = abab: the answer is 6, from four letters plusabaandbab. Palindromes can overlap, and each is counted by its own center.
Follow-ups interviewers ask
- Can you do better than O(n^2) time?
- Yes. Manacher's algorithm counts palindromes in O(n). It reuses the radius found for a mirrored center inside the current rightmost palindrome. Each character is then expanded at most a constant number of times, and the sum of all radii is the answer. For n up to 1000, center expansion is the better choice in an interview because it is much shorter to write.
- How would you return the longest palindromic substring instead of the count?
- Use the same center expansion, but track the best start and length instead of a counter. After each expansion, compare its final width with the best so far and keep the larger one. The time stays O(n^2) and the space stays O(1) beyond the returned substring.
- What if the string is very large and does not fit in memory?
- A palindrome can be as long as the whole string, so you cannot bound the window in general. If you can cap the palindrome length at a known k, stream the text with a sliding window of size k and expand centers inside it. Without a cap, you need random access to the data, for example through memory-mapped storage, and then center expansion or Manacher works on it.
Palindromic Substrings FAQ
What is the time complexity of Palindromic Substrings?
The best simple solution runs in O(n^2) time and O(1) extra space, where n is the length of s. There are 2n - 1 centers and each expansion moves at most n / 2 steps. The brute force is O(n^3), and the DP table is O(n^2) time with O(n^2) space. Manacher's algorithm reaches O(n).
Why use expanding from the center for Palindromic Substrings?
A palindrome is determined by its center, and a wider palindrome is built from a narrower one with the same center. Expanding from a center checks only the two new outer characters at each step. This removes the repeated inner comparisons of the brute force and avoids the table of the DP solution.
Why are there 2n - 1 centers in LeetCode 647?
Odd-length palindromes center on one of n characters. Even-length palindromes center on one of the n - 1 gaps between neighbors. Together that is 2n - 1 centers. In code you loop i over n indices and call the expansion twice, with (i, i) and (i, i + 1). The last even call is out of bounds and counts nothing.
Can Palindromic Substrings be solved in O(1) extra space?
Yes. Center expansion needs only the two pointers and a counter, so it uses O(1) extra space with O(n^2) time. The DP version needs O(n^2) space. You could cut that to O(n) with rolling rows, but the center method is simpler and uses less.
Does Palindromic Substrings count duplicate substrings separately?
Yes. Each substring is identified by its start and end index, so equal text at different positions counts again. For aaa the answer is 6, because a appears at three positions and aa at two. A set of strings would give 3 and is wrong.
How is Palindromic Substrings different from Longest Palindromic Substring?
Both use the same center expansion. Here you add one for every successful expansion step. In Longest Palindromic Substring (LeetCode 5) you record the widest palindrome found. The loops, the two kinds of centers and the O(n^2) time are the same.
Asked at
See which companies ask this — Pro
Related problems
- Longest Palindromic Substring · same technique: Expanding From Center (Palindromes)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers
- Reverse Integer · same pattern: Two Pointers
- Two Sum II - Input Array Is Sorted · same pattern: Two Pointers
- 4Sum · same pattern: Two Pointers