Interval DP
Matrix-chain multiplication, optimal BSTs and polygon triangulation.
Six matrices can be parenthesized in 42 ways, twenty in about 1.8 billion, and the costs can differ by orders of magnitude. One table finds the best order; a monotonicity found by Knuth cuts the closely related optimal-search-tree problem to ; and Hu and Shing turned matrix chains into triangulated polygons and solved them in .
What you’ll learn
- Count parenthesizations with Catalan numbers, prove the matrix-chain recurrence by cut-and-paste, and count the DP's work exactly: split evaluations.
- Map matrix chains to triangulations of a convex polygon (Hu and Shing), and contrast convex polygons with minimum-weight triangulation of point sets, which is NP-hard.
- Derive the optimal-BST and pile-merging recurrences, and prove that Knuth's monotone roots make the DP by a telescoping sum; place Hu–Tucker and Garsia–Wachs.
- Read CYK parsing and RNA folding as interval DPs, and state their links to Boolean matrix multiplication, -clique and truly subcubic algorithms.
Matrix chains, exactly
Let be the number of ways to parenthesize a product of matrices. The last multiplication splits the chain into the first and the last factors, so
whose solution is the Catalan number . Since , exhaustive search is exponential: , , .
How many ways are there to parenthesize a product of 5 matrices?
Show the answer
14
, using , , . That is .
Every parenthesization of () ends with one multiplication for some , of a matrix by a matrix. Its cost splits into three independent parts:
Cut and paste. If an optimal parenthesization with last split computed the left part suboptimally, replacing that part by an optimal one would lower the total, a contradiction. So both parts are optimal, and the optimum is at least the minimum over :
Conversely, for every the optimal parts combined give a valid parenthesization, so the minimum over is achievable. Hence equality.
Exact work. Each triple is one split evaluation. Choosing among the boundaries is choosing 3 of items:
Triangulations: the same DP in disguise
Hu and Shing (1982) observed that a chain of matrices is a convex polygon with vertices , where vertex carries the weight and the side plays the role of the whole product. Multiplying costs , the product of the weights of the triangle ; the two sub-chains are the two sub-polygons on either side of that triangle. By induction, parenthesizations correspond exactly to triangulations, and a parenthesization's cost is the sum over the triangles of the products of their vertex weights.
| Matrix chain | Convex polygon |
|---|---|
| matrices, dimensions | vertices with weights |
| One multiplication | One triangle |
| Cost | Product of the triangle's three vertex weights |
| multiplications | triangles in every triangulation |
| parenthesizations | triangulations |
The geometric view paid off. In two papers (1982, 1984) Hu and Shing gave an algorithm for matrix-chain ordering, still the fastest known exact algorithm. Its correctness proof had a gap, a lemma whose published proof was wrong, found and repaired by Schwartz and Weiss (2019): a reminder that celebrated algorithms deserve re-checking.
The convexity matters. For a convex polygon, the minimum-weight triangulation (least total length of the edges used) is the interval DP above. For an arbitrary set of points in the plane, minimum-weight triangulation is NP-hard (Mulzer & Rote, 2008): without a convex boundary, a triangle no longer splits the problem into two independent intervals.
Think first How many triangulations does a convex hexagon have, and which matrix chain does it correspond to?
14, and a chain of 5 matrices: a polygon with vertices corresponds to matrices, and both are counted by . (42 would be a heptagon, or 6 matrices.)
Optimal search trees and Knuth's speedup
Keys are searched with frequencies . A binary search tree on them costs , the total number of comparisons. Whichever key is the root of the range , the keys before it form its left subtree and the keys after it its right subtree, and hanging the whole range one level deeper adds each of its frequencies once:
Filled by increasing length, that is . (Knuth's 1971 paper also weighs unsuccessful searches, which end between keys; the structure is the same.)
Search for the root of only between the roots of its two sub-ranges. The cell then tries this many roots:
Sum over the cells of one length , for . The sum telescopes: the first root of one cell is the second root of the next cell, with opposite signs:
Each of the lengths costs , so the whole table costs instead of , with the same answer:
def merge_cost(w):
"""Merge adjacent piles until one remains; a merge costs the total size. O(n^2) by Knuth."""
n = len(w)
P = [0]
for x in w:
P.append(P[-1] + x) # piles i..j weigh P[j+1] - P[i]
cost = [[0] * n for _ in range(n)]
opt = [[i] * n for i in range(n)] # opt[i][j]: a best last split; opt[i][i] = i
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
cost[i][j] = float('inf')
for k in range(opt[i][j - 1], min(opt[i + 1][j], j - 1) + 1): # Knuth's window
c = cost[i][k] + cost[k + 1][j]
if c < cost[i][j]:
cost[i][j], opt[i][j] = c, k
cost[i][j] += P[j + 1] - P[i]
return cost[0][n - 1]
print(merge_cost([4, 1, 3, 2])) # 20Merging adjacent piles at the cost of their total size is the same kind of DP, with the weights on the leaves. On 400 random piles the window loop ran about times, against split evaluations without it, with the same result.
Pile merging is the optimal alphabetic tree problem: a binary tree whose leaves carry the weights in a fixed left-to-right order, minimizing weight depth. It is Huffman coding with the order of the letters kept. Hu and Tucker (1971) solved it in , and Garsia and Wachs (1977) found a simpler algorithm with the same bound that ends up making the same comparisons in the same order. Knuth's is the general-purpose tool; these algorithms exploit the structure of one problem.
Why does Knuth's speedup bring the optimal-BST table from to ?
- Each cell needs only candidate roots
- The root windows along one length telescope, so all the cells of one length together try roots
- It skips the ranges longer than
- The root of every range is its median key
Show the answer
B. The root windows along one length telescope, so all the cells of one length together try roots
A single cell may still try many roots; what is bounded is the total per length: . With lengths, in all.
Parsing and folding: interval DP at scale
A context-free grammar in Chomsky normal form has only rules and . The CYK algorithm (Cocke; Younger, 1967; Kasami, 1965) decides whether such a grammar generates a string of length with an interval table: is the set of variables that derive , and iff some rule and some split have and . That is time for a grammar with rules.
def cyk(s, unary, binary, start='S'):
"""unary: rules (A, 'a'); binary: rules (A, B, C) for A -> B C. s is non-empty."""
n = len(s)
T = [[set() for _ in range(n)] for _ in range(n)] # T[i][j]: variables deriving s[i..j]
for i, ch in enumerate(s):
T[i][i] = {A for A, a in unary if a == ch}
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for k in range(i, j): # split: s[i..k] + s[k+1..j]
for A, B, C in binary:
if B in T[i][k] and C in T[k + 1][j]:
T[i][j].add(A)
return start in T[0][n - 1]
unary = [('L', '('), ('R', ')')]
binary = [('S', 'S', 'S'), ('S', 'L', 'R'), ('S', 'L', 'A'), ('A', 'S', 'R')] # balanced parentheses
print(cyk('(()())', unary, binary), cyk('())(', unary, binary)) # True FalseA grammar for non-empty balanced parentheses in Chomsky normal form; it agrees with a simple counter on every string of up to 10 brackets.
RNA folding is the biological cousin. An RNA strand folds onto itself by pairing complementary bases (A–U, G–C and the weaker G–U), and in a secondary structure no two pairs cross. Maximizing the number of non-crossing pairs (Nussinov, Pieczenik, Griggs & Kleitman, 1978) is an interval DP: the first base of is either unpaired or paired with some , which splits the rest into and :
time. Practical folding software minimizes a free energy with richer recurrences of the same interval shape.
Key takeaways
- Matrix chains have parenthesizations, but the interval DP over split points finds the cheapest with exactly split evaluations.
- Parenthesizations are triangulations of a convex polygon with vertex weights; Hu and Shing exploited this for . Without convexity, minimum-weight triangulation is NP-hard.
- Knuth's monotone roots, , make optimal BSTs and pile merging by a telescoping sum; alphabetic trees even have algorithms (Hu–Tucker, Garsia–Wachs).
- CYK parsing and RNA folding are cubic interval DPs; parsing is equivalent to Boolean matrix multiplication (Valiant, Lee), and clique-based lower bounds explain why combinatorial algorithms stay near-cubic.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How does the number of parenthesizations of matrices grow?
- Like
- Like
- Like , up to a constant factor
- Polynomially, like
Show the answer
C. Like , up to a constant factor
It is the Catalan number , and . Exponential, so exhaustive search is hopeless, while the interval DP needs only split evaluations.
In Hu and Shing's correspondence, what is the cost of the triangle with vertices ?
- The triangle's area
Show the answer
B.
Multiplying a matrix by a matrix costs , the product of the three vertex weights.
Minimum-weight triangulation takes time for a convex polygon but is NP-hard for a general set of points. What breaks the interval DP for point sets?
- Point sets can have more than triangles
- Without a convex boundary in a fixed cyclic order, a triangle does not split the remaining points into two independent ranges
- Edge lengths are irrational numbers
- The number of triangulations is larger than a Catalan number
Show the answer
B. Without a convex boundary in a fixed cyclic order, a triangle does not split the remaining points into two independent ranges
In a convex polygon a triangle on the edge with apex leaves two sub-polygons, the ranges and . Inner points destroy this: the remaining region is not described by a range, and Mulzer and Rote (2008) proved the problem NP-hard.
Which statement about context-free parsing is correct?
- CYK runs in time for every grammar in Chomsky normal form
- CYK runs in time, and Valiant's reduction to Boolean matrix multiplication brings recognition down to
- No algorithm can recognize context-free languages faster than
- CYK only works for unambiguous grammars
Show the answer
B. CYK runs in time, and Valiant's reduction to Boolean matrix multiplication brings recognition down to
CYK is an interval DP with cells, splits per cell and rules per split. Valiant's is subcubic, and Lee's converse shows that any substantially faster parser would also speed up Boolean matrix multiplication.
Further reading
- T. C. Hu & M. T. Shing, "Computation of matrix chain products, Part I," SIAM Journal on Computing 11(2) (1982), 362–373; "Part II," 13(2) (1984), 228–251.
- D. E. Knuth, "Optimum binary search trees," Acta Informatica 1 (1971), 14–25.
- F. F. Yao, "Efficient dynamic programming using quadrangle inequalities," STOC 1980, 429–435.
- A. M. Garsia & M. L. Wachs, "A new algorithm for minimum cost binary trees," SIAM Journal on Computing 6(4) (1977), 622–642.
- A. Abboud, A. Backurs & V. Vassilevska Williams, "If the current clique algorithms are optimal, so is Valiant's parser," FOCS 2015; SIAM Journal on Computing (2018).