๐๏ธ Day 32: Palindromic Substrings with Center Expansion
๐ง Concept Deep Dive
Another elegant way to count palindromic substrings โ without the full DP table โ is center expansion. Every palindrome is centered around a single character (odd length) or between two characters (even length).
Instead of checking all substrings, we just expand around each possible center.
There are 2n - 1 possible centers for a string of length n.
๐ฏ Visual Intuition
For s = "aba":
- Centers:\
a(index 0)\b(index 1)\a(index 2)\ Betweena-b\ Betweenb-a
Each of these centers is expanded outward as long as the characters match.
aba
^
^ ^
aba
^^^ โ expands out
aba
^ ^ โ also expands๐ ๏ธ Key Patterns
๐ Expand Around Center
function countSubstrings(s: string): number {
let count = 0;
for (let center = 0; center < 2 * s.length - 1; center++) {
let left = Math.floor(center / 2);
let right = left + (center % 2);
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
}
return count;
}๐ Example
Input: "abcba"\
Output: 7
Palindromes:\
"a", "b", "c", "b", "a", "bcb", "abcba"
Same result as Day 31 โ but no DP table!
๐งช Homework
- Implement
countSubstrings(s: string)using center expansion - Modify it to print each palindromic substring found
- Compare runtime vs. DP solution from Day 31 on larger inputs
๐ง Big-O Cheat Sheet
- Time:
O(n^2)โ worst case we expandntimes for2n-1centers - Space:
O(1)โ constant space!
๐ฎ Up Next
โถ๏ธ Day 33: Longest Palindromic Substring