Palindromic Substrings
LeetCode 647 · Medium · solution, intuition & step-by-step walkthrough
Count expansions from 2n-1 centres.
This is how I solved Palindromic Substrings (LeetCode 647), a medium problem from the Palindrome / Interval DP pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every palindromic substring has a centre. Expanding from each centre, every successful step outward is one more palindrome — so count steps instead of tracking strings.
Approach
- 1
expand_both_side returns how many palindromes share this centre.
- 2
Sum over odd centres (i, i) and even centres (i, i+1).
How I solved it
Expand around centrePythonO(n²) time · O(1) space
class Solution:
def countSubstrings(self, s: str) -> int:
#expand both side
def expand_both_side(s,start,end):
count = 0
while start>=0 and end<len(s):
if s[start]!=s[end]:
break
count+=1
start-=1
end+=1
return count
count=0
for i in range(len(s)):
count+=expand_both_side(s,i,i)
count+=expand_both_side(s,i,i+1)
return count
Palindromic Substrings — FAQ
What is the intuition behind Palindromic Substrings?
Every palindromic substring has a centre. Expanding from each centre, every successful step outward is one more palindrome — so count steps instead of tracking strings.
How do you solve Palindromic Substrings (LeetCode 647)?
1. expand_both_side returns how many palindromes share this centre. 2. Sum over odd centres (i, i) and even centres (i, i+1).
What is the time and space complexity of Palindromic Substrings?
Time: O(n²). Space: O(1). (Accepted approach: Expand around centre.)
What are common mistakes in Palindromic Substrings?
Count every expansion, not just the longest one.