Palindromic Substrings (LeetCode 647): Solution and Explanation

Medium
String
Dynamic Programming

Given a string, count how many of its substrings read the same forward and backward. Substrings at different positions count separately even when they contain the same characters.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force generates all O(n²) substrings and checks each for being a palindrome, which costs up to O(n) per check, for O(n³) overall. With a string of length 1,000 that is around a billion character comparisons, which is too slow, and most of the work repeats: checking "abcba" re-checks "bcb" inside it.

Flip the viewpoint from substrings to centers. Every palindrome is symmetric around a center, and if you know a substring centered at some point is a palindrome, the one that extends it by one character on each side is a palindrome exactly when those two new characters match. So instead of testing each substring from scratch, you can start at a center and grow outward, counting one palindrome for every successful step and stopping at the first mismatch.

There are two kinds of centers. Odd-length palindromes like "aba" are centered on a single character, while even-length ones like "abba" are centered between two characters. A string of length n has n of each, so about 2n centers in total. Expanding from each one counts every palindromic substring exactly once, because each palindrome has a unique center, and it needs no extra memory.

Approach: Expand around every center

  1. Initialize res = 0.
  2. For each index i, start an odd-length expansion with l = r = i.
  3. While l and r are in bounds and s[l] == s[r], add 1 to res and move l left and r right.
  4. Then start an even-length expansion with l = i and r = i + 1, and repeat the same loop.
  5. After every center has been expanded, return res.

Step-by-step example

s = "aaa"
  1. i = 0, odd center: "a" at (0,0) counts, res = 1; l goes out of bounds. Even center (0,1): "aa" counts, res = 2; then l goes out of bounds.
  2. i = 1, odd center: "a" at (1,1) counts, res = 3; expanding to (0,2) gives "aaa", res = 4; then out of bounds.
  3. i = 1, even center (1,2): "aa" counts, res = 5; expanding to (0,3) is out of bounds.
  4. i = 2, odd center: "a" at (2,2) counts, res = 6. The even center (2,3) is out of bounds.
  5. Return 6: three single letters, two copies of "aa" and one "aaa".

Code: Python, Java, C++

1class Solution:
2    def countSubstrings(self, s: str) -> int:
3        res = 0
4        
5        for i in range(len(s)):
6            # odd length
7            l, r = i, i
8            while l >= 0 and r < len(s) and s[l] == s[r]:
9                res += 1
10                l -= 1
11                r += 1
12            
13            # even length
14            l, r = i, i + 1
15            while l >= 0 and r < len(s) and s[l] == s[r]:
16                res += 1
17                l -= 1
18                r += 1
19        return res

Time and space complexity

Time

O(n²)

There are 2n - 1 meaningful centers and each expansion can run up to n / 2 steps, as happens with a string of identical letters, so the total is O(n²). For typical strings with few long palindromes, most expansions stop after a step or two, so it runs much faster than the bound.

Space

O(1)

Only a counter and two pointers are used. No table or substring copies are created.

Other approaches

2D dynamic programming (time O(n²), space O(n²))

Let dp[i][j] be true when s[i:j + 1] is a palindrome, which holds when s[i] == s[j] and the inside dp[i + 1][j - 1] is a palindrome or has length at most one. Count the true cells. Same time, but it needs a quadratic table.

Manacher's algorithm (time O(n), space O(n))

Transforms the string with separators and reuses mirrored palindrome radii to compute every center's radius in linear time. The count is the sum of the half radii. It is optimal but rarely expected in interviews.

Common mistakes

  • Expanding only odd-length centers, which misses every even palindrome such as "aa" or "abba".
  • Checking the bounds after comparing characters. The l >= 0 and r < len(s) condition must come first to avoid reading outside the string.
  • Counting distinct palindromes instead of all occurrences. In "aaa", the substring "aa" appears twice and both count.
  • Copying substrings to check them, which adds an O(n) factor that the center expansion avoids entirely.

Frequently asked questions

Why do we need both odd and even centers?

An odd-length palindrome has a middle character, while an even-length one has a middle gap between two characters. Expanding from single characters only finds the first kind, so the second expansion from each adjacent pair is needed to find the rest.

What is the time complexity of counting palindromic substrings?

Expanding around centers is O(n²) time and O(1) space. The DP table approach is also O(n²) time but uses O(n²) space, and Manacher's algorithm gets it down to O(n).

How is this related to longest palindromic substring?

Both use the same center expansion. Here you add one for every successful expansion step; for the longest version you instead record the widest window reached from any center.