Palindrome Partitioning II

Cut a string into palindromes with as few cuts as possible, using the best answer for every prefix.

Given a string s, cut it into pieces so that every piece is a palindrome: it reads the same forwards and backwards, like "level" or "noon". Return the smallest number of cuts that does this.

Example 1
Input: s = "aab"
Output: 1
Explanation: "aa" | "b" needs one cut.
Example 2
Input: s = "a"
Output: 0
Example 3
Input: s = "abccbc"
Output: 2
Explanation: "a" | "bccb" | "c".
Solution

The Idea

One letter on its own always reads the same both ways, so cutting before every letter always works. In Example 3, "abccbc" has six letters, and five cuts turn it into six one-letter pieces. The real question is how few cuts are enough.

Example 3 needs only two: "a" | "bccb" | "c". The middle piece, "bccb", is the same backwards, so it stays whole. But six letters have five gaps between them, and each gap can be cut or not, so there are 32 ways to cut the string. That number doubles with every extra letter. Can we find the best split without trying them all?

Look at the end of the string instead of the start. Whatever the best split is, its last piece ends at the last letter, and it is a palindrome. In "abccbc" two palindromes end at the last letter: "c" on its own, and "cbc".

If the last piece is "c", the letters before it, "abccb", need their own best split, plus one cut in front of the "c". If the last piece is "cbc", the letters before it are "abc", again plus one cut. So the question for the whole string becomes the same question for a shorter piece from its beginning. Look at the picture below.

The string abccbc at positions 0 to 5, with the fewest cuts up to each position: 0, 1, 2, 2, 1, 2. The palindromes that end at position 5 are c and cbc. Last piece c costs 1 + 1 = 2 cuts, last piece cbc costs 2 + 1 = 3, so position 5 gets 2.

The row labelled "fewest cuts up to here" holds the fewest cuts needed for the letters from position 0 up to each position. Such a piece, taken from the very beginning of a string, is called a prefix. Under position 4 is 1, because "abccb" splits as "a" | "bccb". Under position 2 is 2, because "abc" has no palindrome longer than one letter.

Last piece "c" then costs 1 + 1 = 2 cuts, last piece "cbc" costs 2 + 1 = 3, and the smaller, 2, goes under position 5. That is the answer to Example 3. Every number in the row comes from numbers to its left, so filling the row from left to right always has the numbers it needs ready.

Solution Approach

Turning that into code means seeing why a plain search is slow, then settling two things: what each entry of the cuts table means, and how to check a piece quickly.

Trying every first piece

Why not simply search? Pick a palindrome that starts the string, solve the rest of the string the same way, then step back and pick a longer first piece, keeping the split with the fewest cuts. That pick, solve and step back pattern is called backtracking, and it does give the right answer.

But it answers the same question many times. A run that counts the calls shows it: for a string of ten a's, the search makes 1,024 calls, and asks "what is the fewest cuts from position 5 on?" 16 times. With twenty a's it makes 1,048,576 calls.

The fix is to work out the answer for each prefix once and keep it in a table, so a longer prefix only reads it. Solving every prefix of the string once, shortest first, and reading the stored counts instead of searching again is called dynamic programming.

The cuts table

What does one entry mean? cuts[j] is the fewest cuts that split the prefix ending at position j into palindromes. For "abccbc" the table holds 0, 1, 2, 2, 1, 2, the row in the picture. If the string has n letters, the answer is the last entry, cuts[n - 1].

How is cuts[j] filled? Look at every position i from 0 to j where the letters from i to j, written s[i..j], form a palindrome. That piece can be the last one. If i is 0, the piece is the whole prefix and needs no cut at all. Otherwise the cost is cuts[i - 1] + 1: the best split of the letters before i, plus one cut in front of the piece.

cuts[j] is the smallest of those costs. It starts at j, one cut before every letter except the first, which always works, and each palindrome found can only lower it.

Telling whether a piece is a palindrome

How do we check s[i..j] quickly? Reading it from both ends takes up to j - i steps, and doing that for every pair of positions would make the method n times slower. A shorter piece helps instead: s[i..j] is a palindrome when its two end letters match and the inside, s[i+1..j-1], is a palindrome too.

"bccb" has b at both ends and "cc" inside, so it passes. A piece of one or two letters has no inside to check, so matching ends are enough. The results go into a table of true and false values, isPal[i][j]. The table is filled for one end position j at a time, in increasing order, so the inside piece, which ends at j - 1, is already filled when it is needed.

Java Solution

The loops live in a helper, cutsTable, which returns the whole cuts array so that main can print it. It works in these steps:

  1. First, create the two tables for a string of length n: isPal, an n by n grid of booleans, all false at the start, and cuts, an array of n numbers.
  2. An outer loop moves j from 0 to n - 1, the end of the prefix being solved, and sets cuts[j] to j, the cut-before-every-letter split.
  3. Inside, a second loop moves i from 0 to j, over every place the last piece could begin. When s.charAt(i) equals s.charAt(j), and the piece has at most two letters (j - i < 2) or its inside isPal[i + 1][j - 1] is true, it sets isPal[i][j] to true.
  4. For each such palindrome it updates cuts[j]: to 0 if i is 0, otherwise to the smaller of cuts[j] and cuts[i - 1] + 1.
  5. When both loops are done, cutsTable returns cuts, and minCut, the method that answers the problem, returns its last entry.

The main method runs the three examples, then "aaaa" and "abacaba", which are palindromes as a whole, and "abcd", where no two letters match. Last, it prints the whole cuts table for "abccbc".

Java
import java.util.Arrays;

public class PalindromePartitioningII {

    // cuts[j] = fewest cuts that split the first j + 1 letters, s[0..j], into palindromes
    static int[] cutsTable(String s) {
        int n = s.length();
        boolean[][] isPal = new boolean[n][n];   // isPal[i][j]: s[i..j] reads the same both ways
        int[] cuts = new int[n];
        for (int j = 0; j < n; j++) {
            cuts[j] = j;                         // worst case: a cut before every letter
            for (int i = 0; i <= j; i++) {
                if (s.charAt(i) == s.charAt(j) && (j - i < 2 || isPal[i + 1][j - 1])) {
                    isPal[i][j] = true;          // s[i..j] can be the last piece
                    cuts[j] = (i == 0) ? 0 : Math.min(cuts[j], cuts[i - 1] + 1);
                }
            }
        }
        return cuts;
    }

    public static int minCut(String s) {
        int[] cuts = cutsTable(s);
        return cuts[s.length() - 1];
    }

    public static void main(String[] args) {
        System.out.println(minCut("aab"));
        System.out.println(minCut("a"));
        System.out.println(minCut("abccbc"));
        System.out.println(minCut("aaaa"));
        System.out.println(minCut("abcd"));
        System.out.println(minCut("abacaba"));
        System.out.println("cuts for abccbc: " + Arrays.toString(cutsTable("abccbc")));
    }
}

Running it prints:

Output
1
0
2
0
3
0
cuts for abccbc: [0, 1, 2, 2, 1, 2]

"aab" gives 1, from "aa" | "b", and "abccbc" gives 2, from "a" | "bccb" | "c". The 0 for "aaaa" and the 0 for "abacaba" both come from the i == 0 case: the whole string is one palindrome, so no cut is needed. "abcd" prints 3, a cut in every gap, because no piece longer than one letter reads the same backwards.

Look at the last line: [0, 1, 2, 2, 1, 2] is the row labelled "fewest cuts up to here" in the picture. The drop from 2 to 1 at position 4 is where "bccb" is found, at a cost of cuts[0] + 1 = 1.

Why is the check j - i < 2 and not j - i < 1? Two equal letters side by side, like "aa", have no inside. With j - i < 1, the check reads isPal[i + 1][j - 1] for them, an entry that is never set and stays false. A run with that change prints 2 for "aab" instead of 1, and 1 for "aaaa" instead of 0.

Complexity

The work is the two loops over pairs of positions, and the memory is the two tables.

  • Time: O(n2), because the inner loop visits each pair of positions i <= j once, about n2/2 pairs, and each visit is one letter comparison, one table lookup and at most one minimum.
  • Space: O(n2), because isPal keeps one true or false value for every pair of positions, while cuts adds only n numbers.

Checking palindromes by growing outward from each middle letter, instead of storing isPal, keeps the time at O(n2) and brings the space down to O(n). For more problems built on the same "is this piece a palindrome" table, see Palindromic Substrings.