Lesson 34 of 40DP families
Interval and Palindrome DP
Solve problems over a range i..j by filling a table by length: palindromes, Burst Balloons, cutting sticks and two-player games.
A query planner has to decide the order in which to multiply or join a chain of things, and the order changes the cost by orders of magnitude. A text tool wants the fewest cuts that split a string into palindromes. A game engine asks whether the first player can force a win when both players take from either end of a row. These look unrelated, but they share one shape: the answer for a range i..j is built from answers for smaller ranges inside it. That is interval DP. In 2D Dynamic Programming the two indices were prefixes of two inputs. Here both indices point into the same input, and that one change decides everything about how you fill the table.
The shape: dp[i][j] over a range
Every interval DP has the same skeleton:
- State:
dp[i][j]= the best answer for the piece of input from indexito indexj(a substring, a subarray, a stretch of stick). - Base cases: ranges of length 1 (and sometimes length 0). A single character is a palindrome; a single pile can only be taken.
- Recurrence: either peel the ends (
dp[i+1][j],dp[i][j-1],dp[i+1][j-1]) or choose a split pointkbetweeniandjand combinedp[i][k]withdp[k][j]. - Order: by increasing length. Every range you read is shorter than the one you are writing, so it is already done.
- Answer: usually
dp[0][n-1], the whole input.
The order is the part people get wrong. In the LCS table you went row by row, top to bottom, because each cell read the row above. Here dp[i][j] reads dp[i+1][...], which is the row below. Fill row 0 first and you read zeros that have not been computed yet. The code runs, returns a number, and the number is wrong.
There are two correct orders. The first is by length: an outer loop over length from 2 to n, then i, with j = i + length - 1. You walk the table one diagonal at a time, starting from the main diagonal. The second is i from n-1 down to 0, j from i up: row i+1 is finished before row i starts, and within a row the cell to the left is finished first. Both work. The length order is easier to explain in an interview because it mirrors the reasoning ("shorter ranges first"). The reversed-row order is shorter to write and is common in solutions you will read.
Only the upper triangle (i <= j) means anything. The lower half is unused, so the table costs O(n^2) memory even though half of it is empty.
Longest palindromic subsequence
Given s, find the length of the longest subsequence that reads the same both ways. For "bbbab" the answer is 4 ("bbbb", skipping the a).
Look at the two ends of the range s[i..j]:
- If
s[i] == s[j], both ends can wrap whatever palindrome lives strictly inside:dp[i][j] = dp[i+1][j-1] + 2. - If they differ, at least one end is not in the answer. Drop either and keep the better:
dp[i][j] = max(dp[i+1][j], dp[i][j-1]).
It looks just like LCS, and that is no accident: the longest palindromic subsequence of s equals the LCS of s and reversed(s). That gives you a quick check, but the interval form is the one that generalises.
Length 1: every single character is a palindrome of length 1. The lower triangle is never used.
Press Run (⌘ Enter) to see what happens.When length is 2 and the ends match, dp[i+1][j-1] points at a lower-triangle cell where i+1 > j-1. That cell is 0, which is exactly right for an empty middle. The zero-filled table handles the edge case for free, but say it out loud in an interview so it does not look like luck.
What does this print?
print(longest_pal_subseq("agbdba"), longest_pal_subseq("abcd"))Substring is not subsequence
Longest Palindromic Substring sounds like the same problem, but a substring must be contiguous. You could fill a boolean table is_pal[i][j] = s[i] == s[j] and is_pal[i+1][j-1] in O(n^2) time and O(n^2) space. There is a better tool: expand around the centre. Every palindrome has a centre, either one character (odd length) or the gap between two (even length). There are 2n - 1 centres. From each, grow outward while the ends match. That is O(n^2) time in the worst case ("aaaa…") and O(1) extra space, and it is what most interviewers expect.
Press Run (⌘ Enter) to see what happens.Palindromic Substrings (count them all) falls out of the same loop: every successful expansion step is one more palindrome. The String Algorithms lesson covers the centre expansion in more depth, plus Manacher's algorithm, which gets the longest palindromic substring in O(n).
So when do you still need the is_pal table? When something else asks "is s[i..j] a palindrome?" many times. Palindrome Partitioning II is the classic case.
Palindrome Partitioning II: a table feeding a 1D DP
Split s into pieces that are all palindromes, using the fewest cuts. "aab" needs 1 cut: aa | b.
This is two DPs stacked. First, the interval table answers "is s[i..j] a palindrome?" in O(1) after O(n^2) work. Second, a 1D DP over prefixes: cuts[j] is the fewest cuts for s[0..j]. If the whole prefix is a palindrome, that is 0. Otherwise, try every last piece s[i..j] that is a palindrome and take cuts[i-1] + 1.
Press Run (⌘ Enter) to see what happens.This version uses the second fill order: i from the end down, j from i up. Both loops are O(n^2), so the total is O(n^2). The naive approach, checking each candidate piece with a fresh loop, is O(n^3). Precomputing a "can I use this range?" table and then running a cheaper DP on top is a pattern worth naming. It shows up again in Word Break (in LIS, Subarray and State-Machine DP) and in many partition problems.
Choosing the split: Burst Balloons
Now the second kind of recurrence, where you choose a point k inside the range. Burst Balloons: each balloon has a number. Bursting balloon k earns left * nums[k] * right, where left and right are its current neighbours (1 past either edge). Find the most coins.
The obvious idea is to pick which balloon to burst first and recurse on the two sides. It fails, because after the first burst the two sides are no longer independent: the balloons next to the gap become neighbours, so the left half's score depends on the right half.
The trick is to pick which balloon to burst last in the range. If k is the last balloon between walls i and j, then everything between i and k has already been burst while i and k were still standing, and the same holds on the right. The two halves cannot see each other, because k stands between them the whole time. When k finally goes, its neighbours are the walls i and j themselves.
dp[i][j] = max over k in (i, j) of dp[i][k] + vals[i] * vals[k] * vals[j] + dp[k][j]
Pad the array with a 1 at each end so the walls always exist and the edge rule becomes ordinary multiplication.
Press Run (⌘ Enter) to see what happens.Notice the brute-force checker. When a recurrence feels clever, compare it against an obviously correct exponential version on tiny inputs. That habit catches more DP bugs than staring at the code.
Three nested loops make this O(n^3) time, O(n^2) space.
Same template: cutting a stick, multiplying matrices
Minimum Cost to Cut a Stick: a stick of length L must be cut at given positions, and each cut costs the length of the piece being cut. Add 0 and L to the sorted cut positions, and dp[i][j] is the cheapest way to make every cut strictly between points i and j. Whichever cut k you make first in that piece costs pts[j] - pts[i], and then the two pieces are independent:
Press Run (⌘ Enter) to see what happens.Here "first" works where Burst Balloons needed "last", because a cut really does split the stick into two independent pieces. Always ask which choice makes the two sides independent.
Matrix-chain multiplication is the textbook ancestor. Multiplying a chain of matrices gives the same result in any bracketing, but the number of scalar multiplications can differ enormously. dp[i][j] is the cheapest way to multiply matrices i..j, and k is where the outermost brackets split. You are unlikely to code it in an interview, but it is the cleanest explanation of why the pattern exists, and database query planners face a close cousin when they choose a join order.
Two-player games: score difference
Stone Game and Predict the Winner: piles sit in a row, two players alternate taking a pile from either end, and both play perfectly. Can the first player win?
Tracking two scores is messy. Track one number instead: dp[i][j] = the best margin (my score minus the opponent's) that the player to move can guarantee on piles[i..j]. If I take the left pile, I gain piles[i] and then my opponent becomes the player to move on i+1..j, earning margin dp[i+1][j] against me. So:
dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1])
That subtraction is minimax in one line: my best is what I take minus my opponent's best from the position I leave. The first player wins if dp[0][n-1] > 0 (or >= 0 if ties count as wins, as in Predict the Winner).
Press Run (⌘ Enter) to see what happens.The original Stone Game (even number of piles, odd total) has a famous shortcut: the first player can always win by taking all even-indexed or all odd-indexed piles, so the answer is just True. Mention it if you see it, but the DP is what the follow-ups (Predict the Winner, Stone Game VII) need.
What does this print?
print(first_player_margin([3, 9, 1, 2]))
Top-down versions and recursion depth
Every interval DP can be written as memoised recursion: solve(i, j) with @functools.cache, recursing on smaller ranges. It is often easier to get right first, because you never think about fill order. The recursion goes at most n levels deep (each call shrinks the range), so for n in the hundreds you are within Python's default limit of 1000 frames, but only just once each frame calls a helper. For n near 1000 you need the bottom-up version or a raised limit. Bottom-up is also faster in Python because it avoids a function call and a cache lookup per state.
Recognising and debugging interval DP
Signals in the problem statement:
- The answer for the whole depends on how you split it, merge it or remove things from it, and order matters ("burst", "cut", "merge stones", "remove boxes").
- You take from either end of a row.
- Palindromes over a single string.
nis small (hundreds) and an O(n^3) solution is acceptable.
When it gives wrong answers, check these in order: the fill order (does every cell you read have a shorter range?), the base cases on the diagonal, whether k ranges over the right open or closed interval, and whether the padding or sentinel points are in the array. Then run a brute force on tiny inputs and compare.
Match each problem to its recurrence.
Put the steps of writing an interval DP in order.
- Tap the steps below in the right order.
- interval DP
- DP where dp[i][j] is the answer for the range i..j of one input, built from shorter ranges inside it.
- fill by length
- Loop over range length from small to large, so every sub-range is ready before it is read.
- split point
- The index k that divides a range into two independent subproblems, such as the last balloon or the first cut.
- expand around centre
- Find palindromic substrings by growing outward from each of the 2n - 1 centres. O(n^2) time, O(1) space.
- score difference
- Game DP that stores my score minus the opponent's, so dp = max(take - opponent's best on what remains).
- matrix-chain multiplication
- The classic interval DP: choose where to split a chain of matrix products to minimise total work.