๐๏ธ 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] = trueifs[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 | Tdp[i][j] = trueif:s[i] === s[j]ANDj - i <= 2(length 1 or 2) ORdp[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
- Implement
countPalindromicSubstrings(s: string): number - Print out the DP table for small
s - 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