Palindromic Substrings

Count the number of palindromic substrings.

Pattern

Expand Around Center

This problem follows the Expand Around Center pattern, commonly found in the 1-D Dynamic Programming category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

For each center, expand and count. Handle both odd and even length.

Key Insight

Every single character is a palindrome, so the count starts at n. Each successful expansion adds one more palindrome.

Step-by-step

  1. 1For each center (odd and even), expand outward
  2. 2Count each valid expansion as a palindromic substring
  3. 3Sum the counts for all centers

Pseudocode

count = 0
for i in range(len(s)):
    # Odd-length
    l, r = i, i
    while l >= 0 and r < len(s) and s[l] == s[r]:
        count += 1
        l -= 1; r += 1
    # Even-length
    l, r = i, i + 1
    while l >= 0 and r < len(s) and s[l] == s[r]:
        count += 1
        l -= 1; r += 1
return count
Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(1)
More 1-D Dynamic Programming Problems

Master this pattern with YeetCode

Practice Palindromic Substrings and similar 1-D Dynamic Programming problems with flashcards. Build pattern recognition through active recall.

Practice this problem