๐Ÿ—“๏ธ Day 31: Dynamic Programming on Palindromic Substrings

๐Ÿง  Concept Deep Dive

While backtracking helps list all palindromic partitions, Dynamic Programming can efficiently determine which substrings are palindromes, saving time during repeated checks.

The goal is to fill a dp[i][j] table where:

  • dp[i][j] = true if s[i..j] is a palindrome

This avoids repeated calls to isPalindrome.


๐ŸŽฏ Visual Intuition

For s = "ababa", we want to build:

     a  b  a  b  a
  ----------------
a | T  F  T  F  T
b |    T  F  T
a |       T  F
b |          T
a |             T
  • dp[i][j] = true if:
    • s[i] === s[j] AND
    • j - i <= 2 (length 1 or 2) OR dp[i+1][j-1] === true

๐Ÿ› ๏ธ Key Patterns

๐Ÿงต Fill Palindrome Table with DP

function countPalindromicSubstrings(s: string): number {
  const n = s.length;
  let count = 0;
  const dp = Array.from({ length: n }, () => Array(n).fill(false));

  for (let end = 0; end < n; end++) {
    for (let start = 0; start <= end; start++) {
      if (s[start] === s[end] && (end - start <= 2 || dp[start + 1][end - 1])) {
        dp[start][end] = true;
        count++;
      }
    }
  }

  return count;
}

๐Ÿ“˜ Example

Input: "abcba"

Output: 7

Explanation:

  • Palindromes: "a", "b", "c", "b", "a", "bcb", "abcba"

๐Ÿงช Homework

  1. Implement countPalindromicSubstrings(s: string): number
  2. Print out the DP table for small s
  3. Bonus: Return all unique palindromic substrings using this table

๐Ÿง  Big-O Cheat Sheet

  • Time: O(n^2)
  • Space: O(n^2) for DP table

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 32: Palindromic Substrings with Center Expansion

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

Powered by Wiki|Docs

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

Tri Nguyen
No Copyright

Powered by Wiki|Docs