Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(n3)O(n^3) table finds the best order; a monotonicity found by Knuth cuts the closely related optimal-search-tree problem to O(n2)O(n^2); and Hu and Shing turned matrix chains into triangulated polygons and solved them in O(nlog⁡n)O(n\log n).

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: (n3−n)/6(n^3-n)/6 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 O(n2)O(n^2) 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, kk-clique and truly subcubic algorithms.

Matrix chains, exactly

Let P(n)P(n) be the number of ways to parenthesize a product of nn matrices. The last multiplication splits the chain into the first kk and the last n−kn-k factors, so

P(1)=1,P(n)=∑k=1n−1P(k) P(n−k),P(1)=1,\qquad P(n)=\sum_{k=1}^{n-1}P(k)\,P(n-k),

whose solution is the Catalan number Cn−1=1n(2n−2n−1)C_{n-1}=\frac1n\binom{2n-2}{n-1}. Since Cm∼4m/(m3/2π)C_m\sim4^m/(m^{3/2}\sqrt\pi), exhaustive search is exponential: P(6)=42P(6)=42, P(10)=4862P(10)=4862, P(20)=1,767,263,190P(20)=1{,}767{,}263{,}190.

Predict before you look

How many ways are there to parenthesize a product of 5 matrices?

Show the answer

14

P(5)=P(1)P(4)+P(2)P(3)+P(3)P(2)+P(4)P(1)=5+2+2+5=14P(5)=P(1)P(4)+P(2)P(3)+P(3)P(2)+P(4)P(1)=5+2+2+5=14, using P(1)=P(2)=1P(1)=P(2)=1, P(3)=2P(3)=2, P(4)=5P(4)=5. That is C4=15(84)=14C_4=\tfrac15\binom84=14.

DerivationProof by cut-and-paste
  1. cost=cost(left)+cost(right)+pi pk+1 pj+1\mathrm{cost}=\mathrm{cost}(\text{left})+\mathrm{cost}(\text{right})+p_i\,p_{k+1}\,p_{j+1}

    Every parenthesization of Ai⋯AjA_i\cdots A_j (i<ji<j) ends with one multiplication (Ai⋯Ak)(Ak+1⋯Aj)(A_i\cdots A_k)(A_{k+1}\cdots A_j) for some kk, of a pi×pk+1p_i\times p_{k+1} matrix by a pk+1×pj+1p_{k+1}\times p_{j+1} matrix. Its cost splits into three independent parts:

  2. OPT(i,j)=m[i][k∗]+m[k∗+1][j]+pi pk∗+1 pj+1 ≥ min⁡k(⋯ )\mathrm{OPT}(i,j)=m[i][k^*]+m[k^*+1][j]+p_i\,p_{k^*+1}\,p_{j+1}\ \ge\ \min_{k}(\cdots)

    Cut and paste. If an optimal parenthesization with last split kk 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 kk:

  3. m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi pk+1 pj+1)m[i][j]=\min_{i\le k<j}\big(m[i][k]+m[k+1][j]+p_i\,p_{k+1}\,p_{j+1}\big)

    Conversely, for every kk the optimal parts combined give a valid parenthesization, so the minimum over kk is achievable. Hence equality.

  4. ∑L=2n(n−L+1)(L−1)=(n+13)=n3−n6=Θ(n3)\sum_{L=2}^{n}(n-L+1)(L-1)=\binom{n+1}{3}=\frac{n^3-n}{6}=\Theta(n^3)

    Exact work. Each triple i≤k<ji\le k<j is one split evaluation. Choosing i<k+1<j+1i<k+1<j+1 among the n+1n+1 boundaries 0,…,n0,\dots,n is choosing 3 of n+1n+1 items:

Triangulations: the same DP in disguise

Hu and Shing (1982) observed that a chain of nn matrices is a convex polygon with n+1n+1 vertices V0,…,VnV_0,\dots,V_n, where vertex ViV_i carries the weight pip_i and the side V0VnV_0V_n plays the role of the whole product. Multiplying (A0⋯Ak−1)(Ak⋯An−1)(A_0\cdots A_{k-1})(A_k\cdots A_{n-1}) costs p0pkpnp_0p_kp_n, the product of the weights of the triangle V0VkVnV_0V_kV_n; 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 chainConvex polygon
nn matrices, dimensions p0,…,pnp_0,\dots,p_nn+1n+1 vertices with weights p0,…,pnp_0,\dots,p_n
One multiplicationOne triangle
Cost pipk+1pj+1p_ip_{k+1}p_{j+1}Product of the triangle's three vertex weights
n−1n-1 multiplicationsn−1n-1 triangles in every triangulation
Cn−1C_{n-1} parenthesizationsCn−1C_{n-1} triangulations
The same interval DP solves every "triangulate a convex polygon at least cost" problem whose cost is a sum over triangles, for example the sum of the perimeters of the triangles.

The geometric view paid off. In two papers (1982, 1984) Hu and Shing gave an O(nlog⁡n)O(n\log n) 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 O(n3)O(n^3) 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 n+1=6n+1=6 vertices corresponds to n=5n=5 matrices, and both are counted by Cn−1=C4=14C_{n-1}=C_4=14. (42 would be a heptagon, or 6 matrices.)

Optimal search trees and Knuth's speedup

Keys k1<k2<⋯<knk_1<k_2<\dots<k_n are searched with frequencies f1,…,fnf_1,\dots,f_n. A binary search tree on them costs ∑ifi (depth(ki)+1)\sum_if_i\,(\mathrm{depth}(k_i)+1), the total number of comparisons. Whichever key krk_r is the root of the range ki,…,kjk_i,\dots,k_j, 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:

e[i][j]=min⁡i≤r≤j(e[i][r−1]+e[r+1][j])+W(i,j),W(i,j)=∑l=ijfl,e[i][i−1]=0.e[i][j]=\min_{i\le r\le j}\big(e[i][r-1]+e[r+1][j]\big)+W(i,j),\qquad W(i,j)=\sum_{l=i}^{j}f_l,\qquad e[i][i-1]=0.

Filled by increasing length, that is Θ(n3)\Theta(n^3). (Knuth's 1971 paper also weighs unsuccessful searches, which end between keys; the structure is the same.)

DerivationWhy the monotone window makes the DP O(n²)
  1. root[i+1][j]−root[i][j−1]+1\mathrm{root}[i+1][j]-\mathrm{root}[i][j-1]+1

    Search for the root of [i,j][i,j] only between the roots of its two sub-ranges. The cell then tries this many roots:

  2. ∑i=1n−L+1(root[i+1][i+L−1]−root[i][i+L−2]+1)=root[n−L+2][n]−root[1][L−1]+(n−L+1) ≤ 2n\sum_{i=1}^{n-L+1}\big(\mathrm{root}[i+1][i+L-1]-\mathrm{root}[i][i+L-2]+1\big)=\mathrm{root}[n-L+2][n]-\mathrm{root}[1][L-1]+(n-L+1)\ \le\ 2n

    Sum over the cells of one length L≥2L\ge2, j=i+L−1j=i+L-1 for i=1,…,n−L+1i=1,\dots,n-L+1. The sum telescopes: the first root of one cell is the second root of the next cell, with opposite signs:

  3. ∑L=1nO(n)=O(n2)\sum_{L=1}^{n}O(n)=O(n^2)

    Each of the nn lengths costs O(n)O(n), so the whole table costs O(n2)O(n^2) instead of Θ(n3)\Theta(n^3), with the same answer:

python
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]))             # 20

Merging 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 1.6×1051.6\times10^5 times, against (4003−400)/6≈1.07×107(400^3-400)/6\approx1.07\times10^7 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 ∑\sum weight ×\times depth. It is Huffman coding with the order of the letters kept. Hu and Tucker (1971) solved it in O(nlog⁡n)O(n\log n), 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 O(n2)O(n^2) is the general-purpose tool; these O(nlog⁡n)O(n\log n) algorithms exploit the structure of one problem.

Check your understanding

Why does Knuth's speedup bring the optimal-BST table from Θ(n3)\Theta(n^3) to O(n2)O(n^2)?

  1. Each cell needs only O(1)O(1) candidate roots
  2. The root windows along one length telescope, so all the cells of one length together try O(n)O(n) roots
  3. It skips the ranges longer than n\sqrt n
  4. 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 O(n)O(n) roots

A single cell may still try many roots; what is bounded is the total per length: ∑i(root[i+1][j]−root[i][j−1]+1)≤2n\sum_i(\mathrm{root}[i+1][j]-\mathrm{root}[i][j-1]+1)\le2n. With nn lengths, O(n2)O(n^2) in all.

Parsing and folding: interval DP at scale

A context-free grammar in Chomsky normal form has only rules A→BCA\to BC and A→aA\to a. The CYK algorithm (Cocke; Younger, 1967; Kasami, 1965) decides whether such a grammar generates a string ss of length nn with an interval table: T[i][j]T[i][j] is the set of variables that derive s[i..j]s[i..j], and A∈T[i][j]A\in T[i][j] iff some rule A→BCA\to BC and some split kk have B∈T[i][k]B\in T[i][k] and C∈T[k+1][j]C\in T[k+1][j]. That is O(n3∣G∣)O(n^3\abs{G}) time for a grammar with ∣G∣\abs G rules.

python
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 False

A 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 s[i..j]s[i..j] is either unpaired or paired with some s[k]s[k], which splits the rest into s[i+1..k−1]s[i+1..k-1] and s[k+1..j]s[k+1..j]:

N[i][j]=max⁡(N[i+1][j], max⁡k: si sk pair(1+N[i+1][k−1]+N[k+1][j])),N[i][j]=\max\Big(N[i+1][j],\ \max_{k:\ s_i\,s_k\ \text{pair}}\big(1+N[i+1][k-1]+N[k+1][j]\big)\Big),

O(n3)O(n^3) time. Practical folding software minimizes a free energy with richer recurrences of the same interval shape.

Key takeaways

  • Matrix chains have Cn−1∼4n/n3/2C_{n-1}\sim4^n/n^{3/2} parenthesizations, but the interval DP over split points finds the cheapest with exactly (n3−n)/6(n^3-n)/6 split evaluations.
  • Parenthesizations are triangulations of a convex polygon with vertex weights; Hu and Shing exploited this for O(nlog⁡n)O(n\log n). Without convexity, minimum-weight triangulation is NP-hard.
  • Knuth's monotone roots, root[i][j−1]≤root[i][j]≤root[i+1][j]\mathrm{root}[i][j-1]\le\mathrm{root}[i][j]\le\mathrm{root}[i+1][j], make optimal BSTs and pile merging O(n2)O(n^2) by a telescoping sum; alphabetic trees even have O(nlog⁡n)O(n\log n) 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.

Question 1

How does the number of parenthesizations of nn matrices grow?

  1. Like n!n!
  2. Like 2n2^n
  3. Like 4n/n3/24^n/n^{3/2}, up to a constant factor
  4. Polynomially, like n3n^3
Show the answer

C. Like 4n/n3/24^n/n^{3/2}, up to a constant factor

It is the Catalan number Cn−1=1n(2n−2n−1)C_{n-1}=\frac1n\binom{2n-2}{n-1}, and Cm∼4m/(m3/2π)C_m\sim4^m/(m^{3/2}\sqrt\pi). Exponential, so exhaustive search is hopeless, while the interval DP needs only (n3−n)/6(n^3-n)/6 split evaluations.

Question 2

In Hu and Shing's correspondence, what is the cost of the triangle with vertices Vi,Vk,VjV_i,V_k,V_j?

  1. pi+pk+pjp_i+p_k+p_j
  2. pipkpjp_ip_kp_j
  3. The triangle's area
  4. pipjp_i p_j
Show the answer

B. pipkpjp_ip_kp_j

Multiplying a pi×pkp_i\times p_k matrix by a pk×pjp_k\times p_j matrix costs pipkpjp_ip_kp_j, the product of the three vertex weights.

Question 3

Minimum-weight triangulation takes O(n3)O(n^3) time for a convex polygon but is NP-hard for a general set of points. What breaks the interval DP for point sets?

  1. Point sets can have more than nn triangles
  2. Without a convex boundary in a fixed cyclic order, a triangle does not split the remaining points into two independent ranges
  3. Edge lengths are irrational numbers
  4. 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 ViVjV_iV_j with apex VkV_k leaves two sub-polygons, the ranges [i,k][i,k] and [k,j][k,j]. Inner points destroy this: the remaining region is not described by a range, and Mulzer and Rote (2008) proved the problem NP-hard.

Question 4

Which statement about context-free parsing is correct?

  1. CYK runs in O(n2)O(n^2) time for every grammar in Chomsky normal form
  2. CYK runs in O(n3∣G∣)O(n^3\abs G) time, and Valiant's reduction to Boolean matrix multiplication brings recognition down to O(nω)O(n^\omega)
  3. No algorithm can recognize context-free languages faster than Θ(n3)\Theta(n^3)
  4. CYK only works for unambiguous grammars
Show the answer

B. CYK runs in O(n3∣G∣)O(n^3\abs G) time, and Valiant's reduction to Boolean matrix multiplication brings recognition down to O(nω)O(n^\omega)

CYK is an interval DP with O(n2)O(n^2) cells, O(n)O(n) splits per cell and ∣G∣\abs G rules per split. Valiant's O(nω)O(n^\omega) 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).