Palindrome Partitioning II

Pattern: Partition and interval DP

hard

Cut s into palindromic pieces using the fewest cuts. Record which substrings are palindromes, and let cuts[j] be the fewest cuts for s[0..j]: the last piece is some palindrome s[i..j].

The problem

Return the fewest cuts needed to split s into pieces that are all palindromes.

Think first

  • What is the last piece?
  • How do you know quickly whether s[i..j] is a palindrome?
  • What is the worst case?

Hints

    Brute force, and why it fails

    Try every way to cut: 2ⁿ⁻¹.

    The key insight

    Two tables, palindromes and best cuts, are filled together in O(n²).

    Dry run

    'aab'. 'aa' is a palindrome, then 'b'.

    Step 1 of 2

    The plan

    for j: cuts[j] = j
      for i <= j: if s[i] == s[j] and (j - i < 2 or pal[i+1][j-1]): pal[i][j] = true; cuts[j] = min(cuts[j], 0 if i == 0 else cuts[i-1] + 1)
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Every substring once.

    Edge cases

    • Already a palindrome: 0.
    • All different: n - 1.
    • One character: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int minCut(String s) {
            int n = s.length();
            boolean[][] pal = new boolean[n][n];    // pal[i][j]: s[i..j] is a palindrome
            int[] cuts = new int[n];                // cuts[j]: the fewest cuts for s[0..j]
            for (int j = 0; j < n; j++) {
                cuts[j] = j;                        // at worst, cut between every character
                for (int i = 0; i <= j; i++)
                    if (s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1])) {
                        pal[i][j] = true;
                        cuts[j] = Math.min(cuts[j], i == 0 ? 0 : cuts[i - 1] + 1);   // the last piece is s[i..j]
                    }
            }
            return cuts[n - 1];
        }
    }

    C++

    class Solution {
    public:
        int minCut(string s) {
            int n = static_cast<int>(s.size());
            vector<vector<bool>> pal(n, vector<bool>(n, false));   // pal[i][j]: s[i..j] is a palindrome
            vector<int> cuts(n);                    // cuts[j]: the fewest cuts for s[0..j]
            for (int j = 0; j < n; j++) {
                cuts[j] = j;                        // at worst, cut between every character
                for (int i = 0; i <= j; i++)
                    if (s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1])) {
                        pal[i][j] = true;
                        cuts[j] = min(cuts[j], i == 0 ? 0 : cuts[i - 1] + 1);   // the last piece is s[i..j]
                    }
            }
            return cuts[n - 1];
        }
    };

    Python

    class Solution:
        def minCut(self, s: str) -> int:
            n = len(s)
            pal = [[False] * n for _ in range(n)]   # pal[i][j]: s[i..j] is a palindrome
            cuts = list(range(n))                   # cuts[j]: the fewest cuts for s[0..j]; at worst between every character
            for j in range(n):
                for i in range(j + 1):
                    if s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1]):
                        pal[i][j] = True
                        cuts[j] = min(cuts[j], 0 if i == 0 else cuts[i - 1] + 1)   # the last piece is s[i..j]
            return cuts[-1]

    Common mistakes

    • Checking palindromes from scratch each time (O(n³)).
    • Counting pieces instead of cuts.

    Similar problems