Sub topic 6
Recovering the Optimal Parenthesization
The matrix chain DP from the previous chapter returns one number, the minimum count of scalar multiplications. That number alone is not enough to do the work. To actually multiply the matrices, you need the order: which pairs to multiply first, and which intermediate results to combine after that. This chapter shows how to rebuild that order from the tables the DP already produces.
This chapter assumes you know recursion, 2D lists in Python, and the matrix_chain_order function from the matrix chain chapter. That function fills dp[i][j] and split[i][j] over inclusive intervals of matrices, where matrix i has shape dims[i] x dims[i + 1].
Why the Cost Table Alone Is Not Enough
dp[i][j] tells you how cheap the best plan for A_i..A_j is. It does not record which plan reaches that cost. Each time the inner loop finds a better k, it throws away the earlier candidates. If you want the plan later, you have two options:
- Record the winning
kas you go. This is what thesplittable does. - Search for the winning
kagain afterward, using the finisheddptable.
Both options work. The first is the standard choice because it is simpler and reconstruction runs in O(n) time.
The Split Table as a Tree
split[i][j] = k means that in the best plan for A_i..A_j, the last multiplication combines the product of A_i..A_k with the product of A_{k+1}..A_j. Each of those halves has its own entry in split, so the table describes a binary tree:
- The root is the full interval
(0, n - 1). - An internal node
(i, j)has children(i, k)and(k + 1, j), wherek = split[i][j]. - A leaf is a single matrix
(i, i). Itssplitentry is never read.
A chain of n matrices always gives a tree with n leaves and n − 1 internal nodes, one per multiplication.
Here is the standard example from CLRS: dims = [30, 35, 15, 5, 10, 20, 25]. Its minimum cost is 15125, and its split table gives split[0][5] = 2, split[0][2] = 0, and split[3][5] = 4.
Recursive Reconstruction
An in-order walk of that tree prints the parenthesization. A post-order walk lists the multiplications in the order you can run them, because each product is computed only after both of its operands exist. The program below is self-contained. It rebuilds the tables, prints both views, and checks the recovered plan against the DP's answer.
def matrix_chain_order(dims):
n = len(dims) - 1
INF = float("inf")
dp = [[0] * n for _ in range(n)]
split = [[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] = INF
for k in range(i, j):
cost = dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
if cost < dp[i][j]:
dp[i][j] = cost
split[i][j] = k
return dp[0][n - 1], split
def parenthesize(split, i, j):
if i == j:
return f"A{i}"
k = split[i][j]
return "(" + parenthesize(split, i, k) + " " + parenthesize(split, k + 1, j) + ")"
def multiplication_steps(split, i, j):
"""Return the products in an order where every operand already exists."""
steps = []
def visit(a, b):
if a == b:
return f"A{a}"
k = split[a][b]
left = visit(a, k)
right = visit(k + 1, b)
name = f"T{len(steps)}"
steps.append(f"{name} = {left} x {right}")
return name
visit(i, j)
return steps
def tree_cost(dims, split, i, j):
"""Cost of the plan encoded in split, computed independently of dp."""
if i == j:
return 0
k = split[i][j]
return (tree_cost(dims, split, i, k)
+ tree_cost(dims, split, k + 1, j)
+ dims[i] * dims[k + 1] * dims[j + 1])
dims = [30, 35, 15, 5, 10, 20, 25]
n = len(dims) - 1
cost, split = matrix_chain_order(dims)
print(cost) # 15125
print(parenthesize(split, 0, n - 1)) # ((A0 (A1 A2)) ((A3 A4) A5))
for step in multiplication_steps(split, 0, n - 1):
print(step)
# T0 = A1 x A2
# T1 = A0 x T0
# T2 = A3 x A4
# T3 = T2 x A5
# T4 = T1 x T3
print(tree_cost(dims, split, 0, n - 1) == cost) # TrueEach function visits every tree node exactly once, and each visit does O(1) work aside from building strings. Reconstruction therefore costs O(n). That is small next to the O(n³) table fill.
Iterative Reconstruction
The recursion depth equals the tree's height, and the height can reach n − 1 when every split sits at one end of its interval. Python's default recursion limit is 1000, so a long, lopsided chain can raise RecursionError. An explicit stack avoids that limit:
def parenthesize_iterative(split, i, j):
out = []
stack = [(i, j)]
while stack:
item = stack.pop()
if isinstance(item, str):
out.append(item)
continue
a, b = item
if a == b:
out.append(f"A{a}")
continue
k = split[a][b]
# Pushed in reverse so they pop as: "(", left, " ", right, ")"
stack.append(")")
stack.append((k + 1, b))
stack.append(" ")
stack.append((a, k))
stack.append("(")
return "".join(out)
dims = [30, 35, 15, 5, 10, 20, 25]
cost, split = matrix_chain_order(dims)
print(parenthesize_iterative(split, 0, len(dims) - 2)) # ((A0 (A1 A2)) ((A3 A4) A5))Reconstruction Without a Split Table
If you kept only dp, you can still find each split. At node (i, j), try every k and keep the one where the recurrence reproduces dp[i][j] exactly:
def matrix_chain_dp(dims):
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
def parenthesize_from_dp(dp, dims, i, j):
if i == j:
return f"A{i}"
for k in range(i, j):
if dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1] == dp[i][j]:
return ("(" + parenthesize_from_dp(dp, dims, i, k) + " "
+ parenthesize_from_dp(dp, dims, k + 1, j) + ")")
raise ValueError(f"no split reproduces dp[{i}][{j}]")
dims = [30, 35, 15, 5, 10, 20, 25]
dp = matrix_chain_dp(dims)
print(parenthesize_from_dp(dp, dims, 0, len(dims) - 2)) # ((A0 (A1 A2)) ((A3 A4) A5))This approach saves the second n × n table. In exchange, each node costs O(j − i) to search, so the total reconstruction time rises to O(n²) in the worst case. That is still cheaper than the fill. Exact comparison with == is safe here because the costs are integers. If the costs were floats, you would need a tolerance, and you could pick a different optimal split from the one the DP chose, or find no match at all.
| Approach | Extra space | Reconstruction time | Risk |
|---|---|---|---|
| Store `split` | n² ints | O(n) | Recording `k` in the wrong place |
| Search `dp` afterward | none | O(n²) | Float rounding; tie choice differs |
Ties and Multiple Optimal Plans
When two splits give the same cost, the comparison operator decides which one gets stored. With dims = [1, 1, 1, 1], both splits of the full interval cost 2:
| Comparison in inner loop | Stored `split[0][2]` | Result |
|---|---|---|
| `cost < dp[i][j]` | 0 (smallest `k`) | `(A0 (A1 A2))` |
| `cost <= dp[i][j]` | 1 (largest `k`) | `((A0 A1) A2)` |
Both plans are optimal. If a test compares your parenthesization string against a fixed expected string, a tie can make a correct solution fail. In that case, either match the tie-breaking rule the test expects, or compare costs with tree_cost instead of comparing strings.
Common Errors
- Saving
koutside the improvement branch. Ifsplit[i][j] = kruns on every loop iteration, the table always holdsj - 1, the last candidate. The cost stays right but the plan is wrong. Thetree_costcheck catches this. - Reading
split[i][i]. Leaves have no split. The base casei == jhas to return before the table is indexed. - Mixing inclusive and exclusive bounds. In this chapter's convention, the children of
(i, j)are(i, k)and(k + 1, j). Exclusive formulations, like the burst balloons chapter's open interval(left, right), use(left, k)and(k, right). Copying child indices from one convention into the other produces overlapping or missing matrices. - Calling with
ninstead ofn - 1. The root is(0, len(dims) - 2), not(0, len(dims) - 1).
The split-table pattern applies to any split-point interval DP. In stone merging, for example, the same walk recovers which adjacent groups to merge at each step.
Exercise
For dims = [5, 10, 3, 12, 5, 50, 6], run matrixchainorder and parenthesize. What are the minimum cost and the parenthesization, and what does multiplication_steps list as the first product?
Show answer
The minimum cost is 2010 and the parenthesization is ((A0 A1) ((A2 A3) (A4 A5))). The first step is T0 = A0 x A1, because the post-order walk finishes the left subtree (0, 1) before it starts on the right subtree (2, 5).
Exercise
A teammate's reconstruction prints ((((A0 A1) A2) A3) A4) for every input, but the printed minimum cost is correct. What is the most likely bug?
Show answer
The line split[i][j] = k runs on every iteration of the k loop instead of only inside the if cost < dp[i][j] branch. Every entry then holds j - 1, which always gives a left-deep tree. Moving the assignment into the branch fixes it, and tree_cost would have flagged the mismatch.
Exercise
Why does reconstruction from a stored split table take O(n) time, while searching the dp table takes O(n^2) in the worst case?
Show answer
The tree has n leaves and n - 1 internal nodes. With a split table, each node does one O(1) lookup, so the total is O(n). Without it, each internal node (i, j) tests up to j - i candidate splits. On a left-deep or right-deep tree those interval lengths are n - 1, n - 2, ..., 1, which add up to O(n^2).