SDE & MLE Prep

132. Palindrome Partitioning II

Problem

Return the minimum number of cuts needed to split s into pieces that are all palindromes.

Example: "aab" → 1 ("aa" | "b"); "a" → 0

Constraints: length ≤ 2000.

cuts[i] = min cuts for s[:i]. Expand around every centre; each palindrome s[l..r] gives cuts[r+1] = min(cuts[r+1], cuts[l] + 1). Base cuts[0] = −1.

Complexity: O(n²) time, O(n) space.

class Solution:
    def minCut(self, s: str) -> int:
        n = len(s)
        cuts = [i - 1 for i in range(n + 1)]       # worst case: cut between every char
        for c in range(n):
            for l, r in ((c, c), (c, c + 1)):
                while l >= 0 and r < n and s[l] == s[r]:
                    cuts[r + 1] = min(cuts[r + 1], cuts[l] + 1)
                    l, r = l - 1, r + 1
        return cuts[n]