๐๏ธ Day 39: DP + Backtracking โ Palindrome Partitioning II (Min Cuts)
๐ง Concept Deep Dive
Given a string s, partition it such that every substring is a palindrome, and return the minimum number of cuts needed to make that happen.
Unlike Day 38 where we returned all valid partitions, this time we want the fewest cuts to create only palindromic substrings.
We use DP for memoizing palindromic substrings and compute the minimum cuts dynamically.
๐ฏ Visual Intuition
For s = "aab", the best way to split is:
"aa" | "b"So, only 1 cut is needed.
We use cut[i] to store the min number of cuts needed for substring s[0..i].
๐ ๏ธ Code Pattern: Dynamic Programming + Palindrome Check
function minCut(s: string): number {
const n = s.length;
const cut = Array(n).fill(0);
const isPal = Array.from({ length: n }, () => Array(n).fill(false));
for (let i = 0; i < n; i++) {
let min = i;
for (let j = 0; j <= i; j++) {
if (s[i] === s[j] && (i - j <= 1 || isPal[j + 1][i - 1])) {
isPal[j][i] = true;
min = j === 0 ? 0 : Math.min(min, cut[j - 1] + 1);
}
}
cut[i] = min;
}
return cut[n - 1];
}๐ Example
Input: "aab"
Output: 1
Input: "a"
Output: 0
Input: "abccbc"
Output: 2
// One optimal split: "a | bccb | c"๐งช Homework
- Try implementing it with a recursive + memoization approach.
- Can you print the actual cut partitions?
- What if all characters are the same?
๐ง Big-O Cheat Sheet
- Time:
O(N^2)โ double loop for substring checking - Space:
O(N^2)for palindrome memo table
๐ฎ Up Next
โถ๏ธ Day 40: Hard DP โ Burst Balloons Problem