Partition DP
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Partition DP cuts a sequence into consecutive pieces so that the total cost is as small as possible, by asking what the last piece could be. For each choice you reuse the saved answer for everything before it. It fits any "where should I cut or break the line" problem.
Practical use cases
- Web app: Word wrap in a text editor. A rich-text editor in the browser breaks a paragraph into lines of a given width and wants the least ragged look. Trying each possible last line and reusing the best layout for the words before it gives neat, balanced lines. Greedy filling leaves one very short line at the end.
- Web app: Splitting work into batches. A job runner has 12 ordered tasks and 3 workers, and each worker gets one continuous block. The goal is to keep the heaviest block as light as possible. The cut points are chosen using saved answers for shorter task lists.
- System: Text segmentation and load balancing. Tools that split text without spaces, such as a long web address, into words use this method, and so do systems that divide ordered work among machines. Each one asks where the last cut should go and reuses the saved best answer for everything before it.
The story: Cutting the Mirror Ribbon
Zoya was decorating a school stage with a long ribbon printed with the letters b a n a n a. "Cut the ribbon into pieces," said Mrs. Sharma, "but every piece must be a mirror word (reads the same from both ends). I want as few pieces as possible, because every cut costs scissors time!"
Zoya tried cutting between every letter: six pieces. Too many! Mira said, "Do not decide the first cut. Look at the last piece. If the last piece is a mirror word, the best answer for the letters before it is already in our notebook." So for each beginning of the ribbon, try every possible last piece, keep it if it is a mirror word, and add one to the notebook entry before it.
For the whole ribbon, the last piece "anana" is a mirror word, and before it only "b" is left (1 piece). Total: 2 pieces, one cut. This habit, try every position for the next split, then build on the best answer to the left, is called Partition DP. Matrix chain multiplication is its famous cousin.
How to spot this problem, and where you need it
You have an ordered list that must be cut into consecutive parts, and the best place for one cut depends on all the others.
Signs you need it
- The problem says "split into k parts", "minimise the largest part" or "best way to break the line".
- The parts must stay in the original order and cannot overlap.
- A greedy approach of filling each part as much as possible produces an unbalanced or costly result.
Where to use it in a project
- Text layout features such as word wrap, justified paragraphs and pagination of long content.
- Dividing ordered tasks, files or records into batches for workers.
The solution
Define best(i) as the lowest cost for the first i items. To compute it, try every possible start j for the last piece: the cost is best(j) plus the cost of the piece from j to i. Keep the smallest. Fill best from 0 upwards, and the answer sits at the full length. When the number of pieces is limited, add it as a second index in the table.
Payoff: Before: a paragraph with one very short last line and uneven edges. After: lines balanced across the paragraph, found in a few hundred steps.
Explain it like I am 8
You are cutting a long cake into pieces and each piece must follow a rule. Instead of deciding all cuts at once, you ask: "What could the last piece be?" For each choice, you look in your notebook for the best way to cut the part before it.
How it works, step by step
- Define
dp[i]= fewest pieces for the firstiletters;dp[0] = 0. - Prepare a quick palindrome check
pal[a][b](true if letters a..b read the same both ways), built once from the inside outwards. - For each
i, try every startjof the last piece: ifpal[j][i-1]is true, a candidate isdp[j] + 1. - Keep the smallest candidate as
dp[i]. - Answer:
dp[n] - 1cuts (ordp[n]pieces).
The code in four languages
PHP
<?php
// Fewest cuts so every piece of $s is a palindrome.
function minPalCuts(string $s): int {
$n = strlen($s);
// pal[a][b] is true when s[a..b] reads the same both ways
$pal = array_fill(0, $n, array_fill(0, $n, false));
for ($a = $n - 1; $a >= 0; $a--) {
for ($b = $a; $b < $n; $b++) {
$pal[$a][$b] = $s[$a] === $s[$b] && ($b - $a < 2 || $pal[$a + 1][$b - 1]);
}
}
$dp = array_fill(0, $n + 1, PHP_INT_MAX);
$dp[0] = 0; // zero letters need zero pieces
for ($i = 1; $i <= $n; $i++) {
for ($j = 0; $j < $i; $j++) { // last piece is s[j..i-1]
if ($pal[$j][$i - 1] && $dp[$j] + 1 < $dp[$i]) {
$dp[$i] = $dp[$j] + 1;
}
}
}
return $dp[$n] - 1; // pieces minus one = cuts
}
echo minPalCuts('banana'), "\n"; // 1
echo minPalCuts('aab'), "\n"; // 1JavaScript
// Fewest cuts so every piece of s is a palindrome.
function minPalCuts(s) {
const n = s.length;
// pal[a][b] is true when s[a..b] reads the same both ways
const pal = Array.from({ length: n }, () => new Array(n).fill(false));
for (let a = n - 1; a >= 0; a--) {
for (let b = a; b < n; b++) {
pal[a][b] = s[a] === s[b] && (b - a < 2 || pal[a + 1][b - 1]);
}
}
const dp = new Array(n + 1).fill(Infinity);
dp[0] = 0; // zero letters need zero pieces
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) { // last piece is s[j..i-1]
if (pal[j][i - 1] && dp[j] + 1 < dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
return dp[n] - 1; // pieces minus one = cuts
}
console.log(minPalCuts('banana')); // 1
console.log(minPalCuts('aab')); // 1Java
import java.util.*;
public class Main {
// Fewest cuts so every piece of s is a palindrome.
static int minPalCuts(String s) {
int n = s.length();
// pal[a][b] is true when s[a..b] reads the same both ways
boolean[][] pal = new boolean[n][n];
for (int a = n - 1; a >= 0; a--) {
for (int b = a; b < n; b++) {
pal[a][b] = s.charAt(a) == s.charAt(b) && (b - a < 2 || pal[a + 1][b - 1]);
}
}
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0; // zero letters need zero pieces
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) { // last piece is s[j..i-1]
if (pal[j][i - 1] && dp[j] + 1 < dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
return dp[n] - 1; // pieces minus one = cuts
}
public static void main(String[] args) {
System.out.println(minPalCuts("banana")); // 1
System.out.println(minPalCuts("aab")); // 1
}
}Go
package main
import (
"fmt"
"math"
)
// Fewest cuts so every piece of s is a palindrome.
func minPalCuts(s string) int {
n := len(s)
// pal[a][b] is true when s[a..b] reads the same both ways
pal := make([][]bool, n)
for i := range pal {
pal[i] = make([]bool, n)
}
for a := n - 1; a >= 0; a-- {
for b := a; b < n; b++ {
pal[a][b] = s[a] == s[b] && (b-a < 2 || pal[a+1][b-1])
}
}
dp := make([]int, n+1)
for i := range dp {
dp[i] = math.MaxInt
}
dp[0] = 0 // zero letters need zero pieces
for i := 1; i <= n; i++ {
for j := 0; j < i; j++ { // last piece is s[j..i-1]
if pal[j][i-1] && dp[j]+1 < dp[i] {
dp[i] = dp[j] + 1
}
}
}
return dp[n] - 1 // pieces minus one = cuts
}
func main() {
fmt.Println(minPalCuts("banana")) // 1
fmt.Println(minPalCuts("aab")) // 1
}Time: O(n²) · Extra space: O(n²). The palindrome table and the pieces table both look at every start and end pair once.
Watch out for
- Checking palindromes by reversing the substring every time, which silently adds another factor of n.
- Returning the number of pieces when the question asks for the number of cuts (they differ by one).
- Forgetting dp[0] = 0, so nothing can ever be built.
Quick check
- What do we try for each prefix?
- Every possible position of the last piece
- Only single letters
- Random cuts
- Minimum cuts for "banana" so each piece is a palindrome?
- 0
- 1
- 5
- Pieces vs cuts for 3 pieces?
- 3 cuts
- 4 cuts
- 2 cuts