Interval DP
Solve problems over subarrays by iterating interval length, such as burst balloons and matrix chain.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Interval DP defines a state for every contiguous range i to j and builds answers for longer intervals from shorter ones. A typical transition tries every split point k inside the interval. Matrix chain multiplication, burst balloons and palindrome partitioning all use this shape.
Explained simply
Some problems are about a row of things where the order is fixed but you choose how to group them. Multiplying a chain of matrices, bursting a row of balloons, or cutting a word into palindromes are like this. Interval DP solves them by answering the question for every stretch from position i to position j.
Small stretches are easy. A stretch of one item usually has an obvious answer. A longer stretch is built from shorter ones. Often you try every place k where you could split it into a left part and a right part, and keep the best.
Because longer stretches need shorter ones, you fill the table by length: first every stretch of length 1, then length 2, and so on, up to the whole row. The answer for the whole row sits in dp[0][n - 1].
There are about n^2 / 2 stretches, and each one may try up to n split points, so the usual cost is O(n^3). That is fine for a few hundred items but too slow for many thousands.
Press Play on a diagram to walk through it one step at a time.
- 1Length 1
Base cases on the diagonal.
- 2Grow length
length = 2, 3, ..., n.
- 3Each start i
j = i + length - 1.
- 4Try splits k
Combine dp[i][k] and dp[k+1][j].
- Back to step 1
- 1Length 1
dp[0][0] = dp[1][1] = dp[2][2] = 0
- 2dp[0][1]
10 x 30 x 5 = 1,500
- 3dp[1][2]
30 x 5 x 60 = 9,000
- 4dp[0][2], k = 0
0 + 9,000 + 10 x 30 x 60 = 27,000
- 5dp[0][2], k = 1
1,500 + 0 + 10 x 5 x 60 = 4,500
- 6Answer
4,500 with (AB)C
In depth
Two shapes of interval transition
Split shape: dp[i][j] = best over k of combine(dp[i][k], dp[k + 1][j]) plus a cost for joining the two halves. Matrix chain, merging stones and optimal binary search trees look like this. O(n^2) intervals times O(n) splits gives O(n^3).
Shrink shape: dp[i][j] only looks at slightly smaller intervals, such as dp[i + 1][j - 1], dp[i + 1][j] or dp[i][j - 1]. Palindrome problems look like this: s[i..j] is a palindrome when s[i] == s[j] and s[i + 1..j - 1] is one. No split loop, so O(n^2) time.
Recognising the shape tells you the complexity before you write any code, and it tells you which cells must already be filled.
- Split: try every k in [i, j), usually O(n^3)
- Shrink: peel one end off, usually O(n^2)
- Base cases sit on the diagonal i == j
Two valid fill orders
The most readable order is by length: for length = 2 to n, for i, set j = i + length - 1. Every interval the transition reads is shorter, so it is ready.
The other common order loops i from n - 1 down to 0 and j from i + 1 up to n - 1. When you compute dp[i][j], every dp[i'][j'] with i' > i is done (later rows were filled first), and dp[i][k] with k < j is done (same row, earlier column). Both orders cover the needs of split and shrink transitions. Mixing them up, for example i ascending, reads cells that are still zero and silently gives wrong answers.
- for length in 2..n
- for i; j = i + length - 1
- Easiest to reason about
- for i from n-1 down to 0
- for j from i+1 up to n-1
- Shorter code, same result
Matrix chain: why order matters
Multiplying a p x q matrix by a q x r matrix takes p x q x r scalar multiplications. The product of a chain is the same whatever the bracketing, but the cost is not. A is 10 x 30, B is 30 x 5, C is 5 x 60. (AB)C costs 10 x 30 x 5 + 10 x 5 x 60 = 1,500 + 3,000 = 4,500. A(BC) costs 30 x 5 x 60 + 10 x 30 x 60 = 9,000 + 18,000 = 27,000, six times more.
The DP tries each last multiplication split k: the cost is dp[i][k] + dp[k + 1][j] + dims[i] x dims[k + 1] x dims[j + 1]. To print the best bracketing, store the best k in split[i][j] and recurse on it. Numerical libraries face this exact question when evaluating chained products such as numpy.linalg.multi_dot, which chooses the order for you.
Burst balloons: think about the last move
Bursting balloon k earns nums[left] x nums[k] x nums[right], where left and right are its current neighbours. If you pick the first balloon to burst, its neighbours change and the two sides stop being independent.
The trick is to choose the last balloon k to burst inside an open interval (i, j). While all the others in between burst, k is still standing, so the left part (i, k) and right part (k, j) never touch each other. When k finally bursts, its neighbours are exactly i and j. Pad the array with a 1 on each end so the borders work, and the recurrence is dp[i][j] = max over k of dp[i][k] + nums[i] x nums[k] x nums[j] + dp[k][j]. For [3, 1, 5, 8] the answer is 167, in O(n^3).
- 1Open interval (i, j)
Balloons strictly between i and j.
- 2Pick last k
k bursts after all the others.
- 3Sides are separate
k stands between them the whole time.
- 4Burst k
Neighbours are exactly i and j.
- 5Add up
dp[i][k] + nums[i] x nums[k] x nums[j] + dp[k][j]
Palindromes and speeding things up
A table is_pal[i][j] for all substrings costs O(n^2) time and space and answers "is s[i..j] a palindrome?" in O(1). Counting palindromic substrings is then a count of True cells. For just the longest palindromic substring, expanding around each of the 2n - 1 centres also takes O(n^2) time but only O(1) space, and Manacher's algorithm does it in O(n).
Palindrome partitioning (fewest cuts so every piece is a palindrome) combines both: build is_pal, then a 1D DP cuts[j] = min(cuts[i - 1] + 1) over every palindrome s[i..j]. That is O(n^2) overall rather than O(n^3).
For some split-shaped problems, such as optimal binary search trees, Knuth's optimisation restricts the split range and lowers the time from O(n^3) to O(n^2).
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Define dp over intervals i to j~45m
- 2Iterate by increasing interval length~45m
- 3Solve matrix chain multiplication~45m
- 4Solve palindromic substring problems~45m
Key points
- States O(n^2); with a split loop, total time is O(n^3).
- Iterate by length so smaller intervals are always ready.
- Palindromic substring checks are O(n^2) interval DP without splits.
- Burst balloons chooses the last balloon to burst in each interval.
Key terms
Tap a card to flip it. 0/3 known
Examples
def matrix_chain(dims): # O(n^3), matrices i is dims[i] x dims[i+1]
n = len(dims) - 1
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = min(
dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
for k in range(i, j)
)
return dp[0][n - 1]
print(matrix_chain([10, 30, 5, 60])) # 4500Burst balloons
nums = [3, 1, 5, 8]. Pad it to [1, 3, 1, 5, 8, 1]. dp[i][j] is the most coins from bursting everything strictly between i and j. Fill by gap length (j - i from 2 upwards), try every last balloon k, and read the answer at dp[0][5]. One best order is burst 1, then 5, then 3, then 8: 3 x 1 x 5 + 3 x 5 x 8 + 1 x 3 x 8 + 1 x 8 x 1 = 15 + 120 + 24 + 8 = 167.
def max_coins(nums): # O(n^3) time, O(n^2) space
a = [1] + nums + [1]
n = len(a)
dp = [[0] * n for _ in range(n)]
for gap in range(2, n):
for i in range(n - gap):
j = i + gap
dp[i][j] = max(dp[i][k] + a[i] * a[k] * a[j] + dp[k][j]
for k in range(i + 1, j))
return dp[0][n - 1]
print(max_coins([3, 1, 5, 8])) # 167
print(max_coins([1, 5])) # 10Fewest cuts for a palindrome partition
Cut "aab" so every piece is a palindrome, using as few cuts as possible. Step 1: an interval table pal[i][j] says whether s[i..j] is a palindrome, filled with i going down so pal[i + 1][j - 1] is ready. Step 2: cuts[j] is the fewest cuts for s[0..j]: 0 if the whole prefix is a palindrome, else 1 + cuts[i - 1] for the best palindrome s[i..j]. "aa" plus "b" needs 1 cut. Both steps are O(n^2).
def min_cut(s):
n = len(s)
pal = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
cuts = [0] * n
for j in range(n):
cuts[j] = 0 if pal[0][j] else min(cuts[i - 1] + 1 for i in range(1, j + 1) if pal[i][j])
return cuts[-1]
print(min_cut("aab"), min_cut("abccbc"), min_cut("a")) # 1 2 0Quick reference
- State dp[i][j] covers the contiguous range i..j; answer at dp[0][n - 1]
- Split transitions: O(n^2) states x O(n) splits = O(n^3)
- Fill by length, or i from n-1 down and j from i+1 up
- Matrix chain cost: dp[i][k] + dp[k+1][j] + dims[i] x dims[k+1] x dims[j+1]
- Burst balloons: pad with 1s and choose the last balloon in each open interval
- pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i+1][j-1])
- Store the best split k to print the actual bracketing
- Python handles n up to a few hundred for O(n^3) interval DP
Common mistakes
- Filling by row index instead of by length, reading unfilled cells.
- Off-by-one errors in the dimension indexes of the split cost.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Count the palindromic substrings of s, counting each position separately. Example: "aaa" gives 6.
- Exercise 2medium
Extend matrix chain to also return the best bracketing as a string, like "((AB)C)". Use dims [10, 30, 5, 60].
- Exercise 3hard
A stick of length n must be cut at given positions, in any order. Each cut costs the length of the piece being cut. Return the minimum total cost. Example: n = 7, cuts [1, 3, 4, 5] gives 16.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I recognise an interval DP problem?
- The input is a sequence whose order cannot change, and the answer for a range depends on how you split or shrink that range. Words like merge, burst, cut, bracket or palindrome over a contiguous range are strong hints.
- Why is interval DP usually O(n^3)?
- There are about n^2 / 2 intervals, and each tries up to n split points. Problems without a split loop, like palindrome tables, are O(n^2).
- Should I loop by length or by i descending?
- Both are correct when the transition reads only shorter or inner intervals. Looping by length is easier to explain; i descending is a little shorter to write.