DSA AnimatorDSA animations
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
—
l
—
r
—
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.

How to solve Palindromic Substrings

LeetCode 647 · Medium · Strings · Pattern: Expand Around Center

Why the obvious approach is slow

Checking every substring for being a palindrome is O(n) cubed.

The key idea

Every palindrome has a center: either one character, or the gap between two characters. From each center, expand outward while both ends match, and count each successful expansion.

Remember

2 n −1 centers cover odd and even palindromes. Each successful expansion is one more palindrome.

Run the animation above on your own input, or watch the 1:07 video explanation of Palindromic Substrings with a dry run and Java code.

More Strings problems