Palindromic Substrings - Problem
Count Palindromic Substrings
Given a string
A palindrome is a string that reads the same forwards and backwards (like "racecar" or "aba"). A substring is any contiguous sequence of characters within the original string.
For example, in the string
Your task: Count all palindromic substrings efficiently!
Given a string
s, return the total number of palindromic substrings contained within it.A palindrome is a string that reads the same forwards and backwards (like "racecar" or "aba"). A substring is any contiguous sequence of characters within the original string.
For example, in the string
"abc", we have substrings: "a", "b", "c", "ab", "bc", "abc". Among these, only "a", "b", and "c" are palindromes, so the answer is 3.Your task: Count all palindromic substrings efficiently!
Input & Output
example_1.py โ Basic case
$
Input:
s = "abc"
โบ
Output:
3
๐ก Note:
Three palindromic substrings: "a", "b", "c". Each single character is a palindrome by definition.
example_2.py โ Multiple palindromes
$
Input:
s = "aaa"
โบ
Output:
6
๐ก Note:
Six palindromic substrings: "a" (3 times), "aa" (2 times), "aaa" (1 time). Total = 3 + 2 + 1 = 6.
example_3.py โ Mixed palindromes
$
Input:
s = "aba"
โบ
Output:
4
๐ก Note:
Four palindromic substrings: "a" (at index 0), "b", "a" (at index 2), and "aba". The entire string is also a palindrome.
Visualization
Tap to expand
Understanding the Visualization
1
Single tile mirrors
Every single tile is a perfect mirror by itself
2
Expand from center
From each tile, check if expanding left and right creates mirror patterns
3
Check dual centers
Also check if adjacent tiles can form the center of an even-length mirror
4
Count all patterns
Sum up all valid mirror patterns found
Key Takeaway
๐ฏ Key Insight: Instead of checking every substring individually, expand around each potential center point. This naturally finds all palindromes while avoiding redundant work - like ripples expanding from stones dropped in water!
Time & Space Complexity
Time Complexity
O(nยณ)
O(nยฒ) for generating all substrings ร O(n) for checking each palindrome
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค s.length โค 1000
- s consists of lowercase English letters only
- A single character is always considered a palindrome
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code