Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Knuth’s Optimization & Monge Arrays

Quadrangle inequalities, totally monotone matrices and SMAWK.

In 1971 Knuth noticed that the root of an optimal binary search tree on a range of keys never moves left when a key is added on the right, nor right when a key is added on the left, and that this turns an O(n3)O(n^3) DP into O(n2)O(n^2). In 1980 Frances Yao found the reason, an inequality between the costs of overlapping intervals. In 1987 Aggarwal, Klawe, Moran, Shor and Wilber built on the same inequality an algorithm that finds the minimum of every row of an n×nn \times n matrix while looking at only O(n)O(n) of its n2n^2 entries.

What you’ll learn

  • Define Monge arrays and total monotonicity, prove the local 2 × 2 test and the monotonicity of row minima, and recognize Monge costs.
  • State and prove the Knuth–Yao theorem: the quadrangle inequality and monotonicity of the weights pass to the DP, which makes the optimal splits monotone and the whole table O(n2)O(n^2).
  • Explain the SMAWK algorithm, prove its correctness and its O(n+m)O(n + m) bound, and use it to compute DP layers in linear time.
  • Connect Monge structure to transportation problems, planar shortest paths and fast (min, +) products, and state what remains open.

Monge arrays and total monotonicity

DerivationTwo basic facts
  1. ∑r=ii′−1∑s=jj′−1(A[r][s]+A[r+1][s+1]−A[r][s+1]−A[r+1][s])=A[i][j]+A[i′][j′]−A[i][j′]−A[i′][j]\sum_{r=i}^{i'-1}\sum_{s=j}^{j'-1}\big(A[r][s] + A[r{+}1][s{+}1] - A[r][s{+}1] - A[r{+}1][s]\big) = A[i][j] + A[i'][j'] - A[i][j'] - A[i'][j]

    The local test. If the inequality holds for all adjacent rows and columns, it holds for all i<i′i < i', j<j′j < j': sum the adjacent inequalities over the rectangle, and the inner terms cancel. Checking an n×mn \times m matrix therefore takes O(nm)O(nm) tests, not O(n2m2)O(n^2 m^2).

  2. A[i′][j′]≤A[i′][j]−(A[i][j]−A[i][j′])<A[i′][j]A[i'][j'] \le A[i'][j] - \big(A[i][j] - A[i][j']\big) < A[i'][j]

    Row minima move right. Let c(i)c(i) be the leftmost minimum of row ii. If i<i′i < i' but c(i′)=j<j′=c(i)c(i') = j < j' = c(i), then A[i][j]>A[i][j′]A[i][j] > A[i][j'] (as j′j' is the leftmost minimum of row ii), and the Monge inequality forces row i′i' to prefer j′j' strictly, contradicting the choice of jj:

Matrix or costMonge?Why
f(j−i)f(j - i) for a convex ff, such as ∣i−j∣\abs{i - j} or (i−j)2(i - j)^2yesthe adjacent test is −(f(d+1)−2f(d)+f(d−1))≤0-\big(f(d+1) - 2f(d) + f(d-1)\big) \le 0
(xi−yj)2(x_i - y_j)^2 for sorted xx and yyyesthe cross term −2xiyj-2x_iy_j gives −2(xi′−xi)(yj′−yj)≤0-2(x_{i'} - x_i)(y_{j'} - y_j) \le 0
interval sums P[j]−P[i]P[j] - P[i]yes, with equalitythe four terms cancel exactly
i⋅ji \cdot j, or −(i−j)2-(i - j)^2no: inverse Mongethe inequality holds reversed, so row maxima move right instead
sums of Monge arrays; adding ri+cjr_i + c_jyesthe defining inequality is linear in AA, and ri+cjr_i + c_j contributes zero
Recognizing Monge structure. Distances between points on two convex chains are a geometric source of (inverse) Monge arrays: in a convex quadrilateral the two diagonals are together longer than two opposite sides.
Check your understanding

Which of these n×nn \times n matrices (rows ii, columns jj) is Monge?

  1. A[i][j]=i⋅jA[i][j] = i \cdot j
  2. A[i][j]=∣i−j∣A[i][j] = \abs{i - j}
  3. A[i][j]=−(i−j)2A[i][j] = -(i - j)^2
  4. A[i][j]=min⁡(i,j)A[i][j] = \min(i, j)
Show the answer

B. A[i][j]=∣i−j∣A[i][j] = \abs{i - j}

∣i−j∣=f(j−i)\abs{i - j} = f(j - i) with f(d)=∣d∣f(d) = \abs{d} convex, so its adjacent second differences are at most 0. The other three fail: i⋅ji \cdot j and −(i−j)2-(i-j)^2 have the cross term +(i′−i)(j′−j)+(i' - i)(j' - j) with the wrong sign, and min⁡(i,j)=(i+j−∣i−j∣)/2\min(i, j) = (i + j - \abs{i - j})/2 is inverse Monge.

Knuth’s optimization, proved

Use Yao's form of an interval DP: D(i,i)=0D(i, i) = 0, and for i<ji < j

D(i,j)=w(i,j)+min⁡i<k≤j(D(i,k−1)+D(k,j)),D(i, j) = w(i, j) + \min_{i < k \le j}\big(D(i, k-1) + D(k, j)\big),

with K(i,j)K(i, j) the largest kk achieving the minimum. Merging piles ai,…,aja_i, \dots, a_j into one, paying the size of each merged pile, has this form with w(i,j)=ai+⋯+ajw(i, j) = a_i + \dots + a_j: the last merge joins ai..ak−1a_i..a_{k-1} and ak..aja_k..a_j. Knuth's optimal binary search trees (1971) have the same shape, with the root excluded from both subtrees.

DerivationProof of (1), by induction on j′ − i
  1. D(i,j)+D(i′,j′)≤[w(i,j)+D(i,z−1)+D(z,j)]+[w(i′,j′)+D(i′,y−1)+D(y,j′)]D(i,j) + D(i',j') \le \big[w(i,j) + D(i,z{-}1) + D(z,j)\big] + \big[w(i',j') + D(i',y{-}1) + D(y,j')\big]

    The cases i=i′i = i' or j=j′j = j' are equalities. Take the main case i<i′<j<j′i < i' < j < j', and let y=K(i′,j)y = K(i', j) and z=K(i,j′)z = K(i, j'); suppose z≤yz \le y (the other case is symmetric). Then zz is a legal split for D(i,j)D(i, j) and yy for D(i′,j′)D(i', j'):

  2. D(z,j)+D(y,j′)≤D(z,j′)+D(y,j)D(z, j) + D(y, j') \le D(z, j') + D(y, j)

    The quadrangle inequality of ww trades w(i,j)+w(i′,j′)w(i, j) + w(i', j') for w(i,j′)+w(i′,j)w(i, j') + w(i', j). For the DD terms, z≤y≤j≤j′z \le y \le j \le j' and j′−z<j′−ij' - z < j' - i, so the induction hypothesis applies:

  3. D(i,j)+D(i′,j′)≤w(i,j′)+D(i,z−1)+D(z,j′)⏟D(i,j′)+w(i′,j)+D(i′,y−1)+D(y,j)⏟D(i′,j)D(i,j) + D(i',j') \le \underbrace{w(i,j') + D(i,z{-}1) + D(z,j')}_{D(i,j')} + \underbrace{w(i',j) + D(i',y{-}1) + D(y,j)}_{D(i',j)}

    Regroup: the right side is exactly D(i,j′)D(i, j'), with split zz, plus D(i′,j)D(i', j), with split yy:

  4. D(i,j)+D(j,j′)≤w(i,j′)+D(i,k−1)+D(k,j′)=D(i,j′)D(i,j) + D(j,j') \le w(i,j') + D(i,k{-}1) + D(k,j') = D(i,j')

    The remaining case i<i′=j<j′i < i' = j < j' asks for D(i,j)+D(j,j′)≤D(i,j′)D(i, j) + D(j, j') \le D(i, j'). With k=K(i,j′)≤jk = K(i, j') \le j, split D(i,j)D(i, j) at kk and use the induction hypothesis D(k,j)+D(j,j′)≤D(k,j′)D(k, j) + D(j, j') \le D(k, j') together with the monotonicity w(i,j)≤w(i,j′)w(i, j) \le w(i, j'); the case k>jk > j is symmetric. This is the only place where monotonicity is needed.

DerivationProof of (2): monotone splits
  1. Dk(i,j)+Dk′(i,j+1)≤Dk(i,j+1)+Dk′(i,j)D_k(i,j) + D_{k'}(i,j{+}1) \le D_k(i,j{+}1) + D_{k'}(i,j)

    Write Dk(i,j)=w(i,j)+D(i,k−1)+D(k,j)D_k(i, j) = w(i, j) + D(i, k-1) + D(k, j) for the cost of splitting at kk. For i<k≤k′≤ji < k \le k' \le j, part (1) on k≤k′≤j≤j+1k \le k' \le j \le j + 1 gives D(k,j)+D(k′,j+1)≤D(k,j+1)+D(k′,j)D(k, j) + D(k', j+1) \le D(k, j+1) + D(k', j); add the same ww and D(i,⋅)D(i, \cdot) terms to both sides:

  2. K(i,j)≤K(i,j+1)≤K(i+1,j+1)K(i, j) \le K(i, j+1) \le K(i+1, j+1)

    Take k′=K(i,j)k' = K(i, j) and any k<k′k < k'. Since Dk′(i,j)≤Dk(i,j)D_{k'}(i, j) \le D_k(i, j), the inequality gives Dk′(i,j+1)≤Dk(i,j+1)D_{k'}(i, j+1) \le D_k(i, j+1): no split left of K(i,j)K(i, j) beats it for (i,j+1)(i, j+1), so the largest optimal split cannot move left. The bound K(i,j)≤K(i+1,j)K(i, j) \le K(i+1, j) follows the same way from part (1) on i≤i+1≤k−1≤k′−1i \le i+1 \le k-1 \le k'-1.

python
def merge_piles(a):                        # D[i][j]: least cost to merge piles a[i..j] (inclusive)
    n = len(a)
    P = [0]
    for v in a:
        P.append(P[-1] + v)
    D = [[0] * n for _ in range(n)]
    K = [[i] * n for i in range(n)]        # K[i][i] = i seeds the windows
    for length in range(1, n):
        for i in range(n - length):
            j = i + length
            best, arg = None, None
            for k in range(max(i + 1, K[i][j - 1]), min(j, K[i + 1][j]) + 1):
                v = D[i][k - 1] + D[k][j]  # last merge joins a[i..k-1] and a[k..j]
                if best is None or v <= best:
                    best, arg = v, k       # ties: keep the largest split
            D[i][j], K[i][j] = best + P[j + 1] - P[i], arg
    return D[0][n - 1]

For piles 4,1,3,2,54, 1, 3, 2, 5 it returns 34: merge 1+31 + 3 (4), then 4+44 + 4 (8), and 2+52 + 5 (7), then the last merge (15). On 400 random piles it evaluates about 1.6×1051.6 \times 10^5 splits, roughly n2n^2, where the plain DP evaluates about 1.07×1071.07 \times 10^7, roughly n3/6n^3/6. Tested against the plain DP on 1,000 random inputs.

SMAWK: every row minimum in linear time

Now take an n×mn \times m totally monotone matrix given by an oracle that returns any entry in O(1)O(1), and ask for the leftmost minimum of every row. Scanning costs O(nm)O(nm). Monotone row minima alone allow divide and conquer on the rows: find the middle row's minimum, then search the upper half left of it and the lower half right of it, O((n+m)log⁡n)O((n + m)\log n), which is divide-and-conquer optimization in matrix language. The SMAWK algorithm (Aggarwal, Klawe, Moran, Shor & Wilber, 1987) uses total monotonicity to reach O(n+m)O(n + m):

  1. Reduce. Scan the columns left to right with a stack. Let the top column sit at stack position ss; compare it with the new column cc in row ss. If cc is strictly smaller there, pop the top and compare again; otherwise push cc, unless the stack already holds nn columns, in which case cc is dropped. At most nn columns survive.
  2. Recurse on every other row, with the surviving columns.
  3. Interpolate. Each remaining row's minimum lies between the minima of the rows just above and below it; scan only that range.
DerivationWhy Reduce never discards a needed column
  1. stack[s] is dominated in rows 0,…,s−1\text{stack}[s] \text{ is dominated in rows } 0, \dots, s-1

    Invariant: the column at stack position ss is no candidate for rows 0,…,s−10, \dots, s-1 (some column to its left is at least as small there). It holds when the column is pushed at position ss: it did not beat the column below it in row s−1s - 1, so by total monotonicity it beats it in no earlier row either.

  2. A[s][c]<A[s][t]  ⟹  A[r][c]<A[r][t]∀r≥sA[s][c] < A[s][t] \;\Longrightarrow\; A[r][c] < A[r][t] \quad \forall r \ge s

    Popping is safe. If the new column cc is strictly smaller than the top tt in row ss, total monotonicity makes it strictly smaller in every later row. So tt is dominated in rows ≥s\ge s by cc, and in rows <s< s by the invariant: it is nobody's leftmost minimum. A column dropped from a full stack is likewise dominated in every row.

  3. T(n,m)=O(m)+T ⁣(n2, n)+O(n)  ⟹  T(n,m)=O(n+m)T(n, m) = O(m) + T\!\left(\tfrac{n}{2},\, n\right) + O(n) \;\Longrightarrow\; T(n, m) = O(n + m)

    Cost. Each column is pushed at most once and popped at most once, so Reduce takes O(m)O(m) comparisons and leaves at most nn columns. Interpolation over all the remaining rows scans each surviving column at most twice plus one step per row. With T(n,m)T(n, m) the cost on nn rows and mm columns:

python
def smawk(rows, cols, A):                  # leftmost minimum column of each row; A totally monotone
    if not rows:
        return {}
    stack = []                             # Reduce: at most len(rows) columns survive
    for c in cols:
        while stack and A(rows[len(stack) - 1], c) < A(rows[len(stack) - 1], stack[-1]):
            stack.pop()                    # c beats the top column from this row downward
        if len(stack) < len(rows):
            stack.append(c)
    ans = smawk(rows[1::2], stack, A)      # recurse on every other row
    j = 0
    for i in range(0, len(rows), 2):       # each remaining row: scan between its neighbors' answers
        r = rows[i]
        stop = ans[rows[i + 1]] if i + 1 < len(rows) else stack[-1]
        best = stack[j]
        while stack[j] != stop:
            j += 1
            if A(r, stack[j]) < A(r, best):
                best = stack[j]
        ans[r] = best
    return ans

Call smawk(list(range(n)), list(range(m)), A). On random 104×10410^4 \times 10^4 Monge matrices it evaluates about 2.42.4 entries per row and column, and it agrees with a brute-force scan on 500 random matrices. It is also optimal: a matrix whose rows are all equal is totally monotone, so finding one row's minimum may already require all mm entries, and nn answers must be written.

DP layers in linear time. A layer dpk[i]=min⁡j<i(dpk−1[j]+w(j,i))dp_k[i] = \min_{j < i}\big(dp_{k-1}[j] + w(j, i)\big) is the row-minimum problem for the matrix A[i][j]=dpk−1[j]+w(j,i)A[i][j] = dp_{k-1}[j] + w(j, i), with A[i][j]=+∞A[i][j] = +\infty for j≥ij \ge i. If ww satisfies the quadrangle inequality, adding the column term dpk−1[j]dp_{k-1}[j] keeps the finite part Monge, and the infinite entries form a staircase that keeps the whole matrix totally monotone. SMAWK then computes each layer in O(n)O(n), so kk layers cost O(kn)O(kn), one logarithm better than divide and conquer.

The self-referential form dp[i]=min⁡j<i(dp[j]+w(j,i))dp[i] = \min_{j < i}\big(dp[j] + w(j, i)\big) is harder, because row ii needs entries that depend on earlier answers. For quadrangle-inequality costs, Larmore and Schieber (1991) adapted SMAWK to this online setting in O(n)O(n) time.

Geometry. The original application was to convex polygons: for the vertices of a convex nn-gon, the farthest other vertex of every vertex can be found in O(n)O(n) total, because the distance matrix, suitably cut, is totally monotone for maxima.

Monge structure across algorithms

Transportation. Monge's 1781 memoir on moving earth from cuts to fills gave the property its name. Hoffman (1963) proved that the greedy northwest-corner rule, which ships as much as possible from the first source to the first destination and moves on, solves every transportation problem with a given cost matrix exactly when that matrix is Monge.

Knuth–Yao as total monotonicity. Bein, Golin, Larmore and Zhang (2009) showed that the Knuth–Yao speedup is itself a consequence of total monotonicity of suitably defined matrices, unifying it with SMAWK-style row minima.

Planar graphs. In a planar graph, the distances between vertices on the boundary of one face form (pieces of) Monge matrices, because shortest paths between interleaved boundary pairs must cross. Fakcharoenphol and Rao (2006) built on this a near-linear algorithm for shortest paths with negative weights in planar graphs, and Monge searches remain a core tool of planar-graph algorithms.

Fast distance products. The (min, +) product of two n×nn \times n Monge matrices is Monge and can be computed in O(n2)O(n^2) time with SMAWK, one row at a time. For unit-Monge matrices, which arise from permutations, Tiskin computed the product in O(nlog⁡n)O(n \log n) time; it powers fast semi-local comparisons of strings, such as the longest common subsequence of one string against every substring of another.

Key takeaways

  • A matrix is Monge if A[i][j]+A[i′][j′]≤A[i][j′]+A[i′][j]A[i][j] + A[i'][j'] \le A[i][j'] + A[i'][j] for i<i′i < i', j<j′j < j'; adjacent 2×22 \times 2 tests suffice, and Monge arrays are totally monotone, so their leftmost row minima move right.
  • Knuth–Yao: if ww satisfies the quadrangle inequality and is monotone, the DP inherits the inequality and its largest optimal splits satisfy K(i,j−1)≤K(i,j)≤K(i+1,j)K(i, j-1) \le K(i, j) \le K(i+1, j), so interval DP costs O(n2)O(n^2).
  • SMAWK finds all row minima of an n×mn \times m totally monotone matrix in O(n+m)O(n + m) evaluations by reducing columns with a stack, recursing on half the rows and interpolating; it computes a quadrangle-inequality DP layer in O(n)O(n).
  • Monge structure reaches far beyond DP: greedy transportation (Hoffman), planar shortest paths, and fast distance products for Monge and unit-Monge matrices.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

To verify that an n×nn \times n matrix is Monge, which tests suffice?

  1. All (n2)2\binom{n}{2}^2 choices of two rows and two columns
  2. The (n−1)2(n-1)^2 submatrices of two adjacent rows and two adjacent columns
  3. That every row's minimum lies to the right of the previous row's
  4. The nn diagonal entries
Show the answer

B. The (n−1)2(n-1)^2 submatrices of two adjacent rows and two adjacent columns

Summing the adjacent inequalities over any rectangle telescopes to the inequality for its four corners, so the (n−1)2(n-1)^2 local tests imply all the others.

Question 2

Which of these is not a hypothesis of the Knuth–Yao theorem for D(i,j)=w(i,j)+min⁡i<k≤j(D(i,k−1)+D(k,j))D(i, j) = w(i, j) + \min_{i < k \le j}\big(D(i, k-1) + D(k, j)\big)?

  1. ww satisfies the quadrangle inequality
  2. w(i′,j)≤w(i,j′)w(i', j) \le w(i, j') whenever [i′,j]⊆[i,j′][i', j] \subseteq [i, j']
  3. w(i,j)w(i, j) depends only on the length j−ij - i
  4. The splits are compared by the DP's own values DD
Show the answer

C. w(i,j)w(i, j) depends only on the length j−ij - i

The theorem needs the quadrangle inequality and monotonicity of ww; interval sums of arbitrary non-negative piles satisfy both without depending only on length. The comparison of splits by DD is simply the DP itself.

Question 3

How many entry evaluations does SMAWK need to find all leftmost row minima of an n×mn \times m totally monotone matrix?

  1. O(nm)O(nm)
  2. O((n+m)log⁡n)O((n + m) \log n)
  3. O(mlog⁡n)O(m \log n)
  4. O(n+m)O(n + m)
Show the answer

D. O(n+m)O(n + m)

Reduce keeps at most nn of the mm columns in O(m)O(m) comparisons, the recursion handles half the rows with at most nn columns, and interpolation costs O(n)O(n): T(n,m)=O(m)+T(n/2,n)+O(n)=O(n+m)T(n, m) = O(m) + T(n/2, n) + O(n) = O(n + m).

Question 4

A DP has kk layers dpt[i]=min⁡j<i(dpt−1[j]+w(j,i))dp_t[i] = \min_{j < i}\big(dp_{t-1}[j] + w(j, i)\big), with ww satisfying the quadrangle inequality. What is the best total time among the methods of this lesson and the previous ones?

  1. O(kn2)O(kn^2), since layers depend on each other
  2. O(knlog⁡n)O(kn \log n), the limit of divide and conquer
  3. O(kn)O(kn), with SMAWK on each layer
  4. O(nlog⁡n)O(n \log n), independent of kk
Show the answer

C. O(kn)O(kn), with SMAWK on each layer

Each layer is the row-minimum problem of a totally monotone matrix (a Monge part plus a staircase of infinities), which SMAWK solves in O(n)O(n); kk layers cost O(kn)O(kn).

Further reading

  • D. E. Knuth, "Optimum binary search trees," Acta Informatica 1 (1971).
  • F. F. Yao, "Efficient dynamic programming using quadrangle inequalities," Proceedings of the 12th ACM Symposium on Theory of Computing (1980).
  • A. Aggarwal, M. M. Klawe, S. Moran, P. Shor & R. Wilber, "Geometric applications of a matrix-searching algorithm," Algorithmica 2 (1987), 195–208.
  • R. E. Burkard, B. Klinz & R. Rudolf, "Perspectives of Monge properties in optimization," Discrete Applied Mathematics 70 (1996).
  • W. Bein, M. J. Golin, L. L. Larmore & Y. Zhang, "The Knuth–Yao quadrangle-inequality speedup is a consequence of total monotonicity," ACM Transactions on Algorithms 6 (2009).