← Back to DSA Animator
Palindromic Substrings LC #647 Medium Expand Around Center
Problem

Given a string s, return the number of palindromic substrings in it. A substring is a contiguous sequence of characters within the string.

Example 1
Input: s = "abc"
Output: 3
Constraints: 1 ≤ s.length ≤ 1000  |  s consists of lowercase English letters.
Try Examples
Custom:
Approach
Expand Around Center — Count Every Palindrome
Same centers as LPS: odd (i,i) and even (i,i+1). Each time s[l]==s[r] inside expand, we count one palindromic substring. O(n²) time, O(1) space.
① Intro
② Odd centers
③ Even centers
④ Done
s[l]
?
s[r]
status
Ready
Press Play to begin.
Count & last found
Variables
i (center)
l (left)
r (right)
count
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Total palindromic substrings
Ready 0 / 0
Select an example and press Play.
Algorithm
1
Initialize count = 0
2
For each i, call expand(i,i) and expand(i,i+1)
3
In expand: while s[l]==s[r], increment count, then l--, r++
4
Return total count
Time
O(n²)
Space
O(1)
Why It Works

Every palindrome has a center. Listing odd and even centers covers all palindromic substrings exactly once per center expansion path.

Why count each step? When s[l..r] is a palindrome, that contiguous substring is valid. The inner while discovers nested palindromes from the center outward; each layer is a distinct substring.

vs. LPS (LC 5): Longest palindrome tracks only the maximum length; here we add 1 to count for every palindrome we see.