๐Ÿ—“๏ธ 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

  1. Try implementing it with a recursive + memoization approach.
  2. Can you print the actual cut partitions?
  3. 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

This page was last edited on 2025-08-01 10:24

Powered by Wiki|Docs

This page was last edited on 2025-08-01 10:24

Tri Nguyen
No Copyright

Powered by Wiki|Docs