Skip to content

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.

26 min read0/6 questions

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 index i to index j (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 point k between i and j and combine dp[i][k] with dp[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.

Longest palindromic subsequence of bbbab, filled by diagonals
j=0j=1j=2j=3j=4
i=0 b1
i=1 b1
i=2 b1
i=3 a1
i=4 b1

Length 1: every single character is a palindrome of length 1. The lower triangle is never used.

1/5
Python
def longest_pal_subseq(s): n = len(s) if n == 0: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 # inner range; 0 when length == 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][n - 1] assert longest_pal_subseq("bbbab") == 4 # "bbbb"assert longest_pal_subseq("cbbd") == 2 # "bb"assert longest_pal_subseq("a") == 1assert longest_pal_subseq("") == 0assert longest_pal_subseq("character") == 5 # "carac"print(longest_pal_subseq("bbbab"), longest_pal_subseq("character"))
Output
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.

Predict the outputPython

What does this print?

print(longest_pal_subseq("agbdba"), longest_pal_subseq("abcd"))
Need a nudge? Hints walk you through it.

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.

Python
def longest_pal_substring(s): best_lo, best_hi = 0, 0 # s[best_lo:best_hi] for centre in range(len(s)): for lo, hi in ((centre, centre), (centre, centre + 1)): # odd, even while lo >= 0 and hi < len(s) and s[lo] == s[hi]: lo -= 1 hi += 1 # the loop overshot by one on each side if hi - lo - 1 > best_hi - best_lo: best_lo, best_hi = lo + 1, hi return s[best_lo:best_hi] def count_pal_substrings(s): count = 0 for centre in range(len(s)): for lo, hi in ((centre, centre), (centre, centre + 1)): while lo >= 0 and hi < len(s) and s[lo] == s[hi]: count += 1 lo -= 1 hi += 1 return count assert longest_pal_substring("babad") in ("bab", "aba")assert longest_pal_substring("cbbd") == "bb"assert longest_pal_substring("bbbab") == "bbb"assert longest_pal_substring("") == ""assert count_pal_substrings("abc") == 3assert count_pal_substrings("aaa") == 6print(longest_pal_substring("bbbab"), count_pal_substrings("aaa"))
Output
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.

Python
def min_cut(s): n = len(s) is_pal = [[False] * n for _ in range(n)] for i in range(n - 1, -1, -1): # i goes DOWN: row i reads row i + 1 for j in range(i, n): if s[i] == s[j] and (j - i < 2 or is_pal[i + 1][j - 1]): is_pal[i][j] = True # cuts[j] = fewest cuts for the prefix s[:j + 1] cuts = [0] * n for j in range(n): if is_pal[0][j]: cuts[j] = 0 continue cuts[j] = min(cuts[i - 1] + 1 for i in range(1, j + 1) if is_pal[i][j]) return cuts[-1] if n else 0 assert min_cut("aab") == 1 # aa | bassert min_cut("a") == 0assert min_cut("ab") == 1assert min_cut("abacdc") == 1 # aba | cdcassert min_cut("abcde") == 4print(min_cut("aab"), min_cut("abacdc"))
Output
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.

Python
from itertools import permutations def max_coins(nums): vals = [1] + nums + [1] # padding: bursting at the edge multiplies by 1 n = len(vals) dp = [[0] * n for _ in range(n)] # dp[i][j]: best for balloons strictly between i and j for length in range(2, n): # gap between the two walls for i in range(n - length): j = i + length best = 0 for k in range(i + 1, j): # k is the LAST balloon burst between i and j coins = dp[i][k] + vals[i] * vals[k] * vals[j] + dp[k][j] best = max(best, coins) dp[i][j] = best return dp[0][n - 1] def brute(nums): best = 0 for order in permutations(range(len(nums))): alive = list(range(len(nums))) total = 0 for b in order: p = alive.index(b) left = nums[alive[p - 1]] if p > 0 else 1 right = nums[alive[p + 1]] if p + 1 < len(alive) else 1 total += left * nums[b] * right alive.pop(p) best = max(best, total) return best assert max_coins([3, 1, 5, 8]) == 167assert max_coins([1, 5]) == 10assert max_coins([]) == 0for case in ([2, 4, 3], [9, 1, 1, 9], [5]): assert max_coins(case) == brute(case), caseprint(max_coins([3, 1, 5, 8]))
Output
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.

Quick check
In Burst Balloons, why does choosing the LAST balloon to burst in (i, j) give a valid recurrence when choosing the FIRST does not?
Need a nudge? A hint rules out a wrong answer.

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:

Python
def min_cost_cut(stick, cuts): pts = [0] + sorted(cuts) + [stick] m = len(pts) dp = [[0] * m for _ in range(m)] # dp[i][j]: cost of every cut strictly between pts[i] and pts[j] for length in range(2, m): for i in range(m - length): j = i + length dp[i][j] = (pts[j] - pts[i]) + min(dp[i][k] + dp[k][j] for k in range(i + 1, j)) return dp[0][m - 1] assert min_cost_cut(7, [1, 3, 4, 5]) == 16assert min_cost_cut(9, [5, 6, 1, 4, 2]) == 22assert min_cost_cut(5, []) == 0print(min_cost_cut(7, [1, 3, 4, 5]))
Output
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).

Python
def first_player_margin(piles): n = len(piles) # dp[i][j]: best (my score - opponent score) when piles[i..j] remain and it is my turn dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = piles[i] for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 dp[i][j] = max(piles[i] - dp[i + 1][j], # take left; opponent then plays i+1..j piles[j] - dp[i][j - 1]) # take right return dp[0][n - 1] assert first_player_margin([5, 3, 4, 5]) == 1assert first_player_margin([1, 5, 2]) == -2 # Predict the Winner: player 1 losesassert first_player_margin([1, 5, 233, 7]) == 222print(first_player_margin([5, 3, 4, 5]), first_player_margin([1, 5, 2]))
Output
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.

Predict the outputPython

What does this print?

print(first_player_margin([3, 9, 1, 2]))
Need a nudge? Hints walk you through it.
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.
  • n is 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 the pairs0/4 matched

Match each problem to its recurrence.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of writing an interval DP in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
You fill dp[i][j] for longest palindromic subsequence with "for i in range(n): for j in range(i + 1, n)". What happens?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.