๐Ÿ—“๏ธ 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)\ Between a-b\ Between b-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

  1. Implement countSubstrings(s: string) using center expansion
  2. Modify it to print each palindromic substring found
  3. Compare runtime vs. DP solution from Day 31 on larger inputs

๐Ÿง  Big-O Cheat Sheet

  • Time: O(n^2) โ€” worst case we expand n times for 2n-1 centers
  • Space: O(1) โ€” constant space!

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 33: Longest Palindromic Substring

This page was last edited on 2025-08-01 09:54

Powered by Wiki|Docs

This page was last edited on 2025-08-01 09:54

Tri Nguyen
No Copyright

Powered by Wiki|Docs