Sub topic 5
Worked Example: Matrix Chain Multiplication
This chapter assumes you already know the earlier parts of the tutorial: what the interval state dp[i][j] means, the base case for single-element intervals, the split-point recurrence, and why tables are filled in order of increasing interval length. It also assumes you can count the cost of multiplying two matrices. Here we apply those pieces to the standard interval DP problem and work through the common mistakes in detail.
The Problem
You have a chain of matrices A0 A1 ... A(n-1), and you want their product. Matrix multiplication is associative, so every parenthesization gives the same result. The amount of work differs, though, and sometimes by a lot.
Multiplying a p × q matrix by a q × r matrix with the textbook algorithm takes p · q · r scalar multiplications. The result is a p × r matrix.
The input is a list dims of length n + 1. Matrix Ai has shape dims[i] × dims[i + 1]. Neighboring matrices share a dimension, which is what makes the chain multipliable.
Take dims = [10, 30, 5, 60]:
| Matrix | Shape |
|---|---|
| A0 | 10 × 30 |
| A1 | 30 × 5 |
| A2 | 5 × 60 |
The chain has two parenthesizations:
| Order | First step | Second step | Total |
|---|---|---|---|
| (A0 A1) A2 | 10·30·5 = 1500, gives 10 × 5 | 10·5·60 = 3000 | 4500 |
| A0 (A1 A2) | 30·5·60 = 9000, gives 30 × 60 | 10·30·60 = 18000 | 27000 |
The bad order does six times as much work. With longer chains the gap can grow without bound.
Why Brute Force Fails
The number of ways to parenthesize a chain of n matrices is the Catalan number C(n-1): 1, 1, 2, 5, 14, 42, 132, ... It grows roughly like 4^n / n^1.5. At 20 matrices there are over 1.7 billion orderings. Listing them all is hopeless, but the orderings share a lot of structure, and that shared structure is what interval DP exploits.
Defining the State
Let dp[i][j] be the minimum number of scalar multiplications needed to compute the product Ai A(i+1) ... Aj. Both bounds are inclusive and index matrices, not entries of dims.
Under this convention the product Ai ... Aj has shape dims[i] × dims[j + 1]. Most bugs in this problem come from that + 1, so check it whenever you write an index.
Base Case
A single matrix costs nothing to "compute":
dp[i][i] = 0for everyi.
There is no empty interval to handle, because every subproblem the recurrence creates contains at least one matrix.
The Recurrence
Look at the last multiplication performed when computing Ai ... Aj. It combines a left product Ai ... Ak with a right product A(k+1) ... Aj for some split k with i ≤ k < j.
- The left product has shape
dims[i] × dims[k + 1]. - The right product has shape
dims[k + 1] × dims[j + 1]. - Multiplying them costs
dims[i] · dims[k + 1] · dims[j + 1].
The two sides do not interact: how you parenthesize the left half has no effect on the cost of the right half. Each side should therefore be computed optimally on its own, which gives the optimal-substructure argument:
dp[i][j] = min over k in [i, j) of
dp[i][k] + dp[k+1][j] + dims[i] * dims[k+1] * dims[j+1]The merge cost depends on k through the shared dimension dims[k + 1]. This is why a greedy choice fails in general. A split that is cheap now can leave behind a pair of shapes that is expensive to combine, and only a full comparison over k catches that.
Filling the Table
Every term on the right of the recurrence is an interval strictly shorter than [i, j]. Looping over length from 2 to n therefore guarantees that each dependency is ready before it is read. Inside each length, the order of i does not matter.
def matrix_chain_order(dims):
# Matrix i has shape dims[i] x dims[i + 1], for i in 0..n-1.
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
cost, split = matrix_chain_order([10, 30, 5, 60])
print(cost) # 4500The function also records split[i][j], the k that achieved the minimum. You only need this table if you want the actual parenthesization, which the next chapter rebuilds from it. Storing it here costs one assignment per improvement.
Tracing the Small Example
With n = 3, the table fills as follows:
| Length | Interval | Candidates | dp | split |
|---|---|---|---|---|
| 2 | [0, 1] | k=0: 0 + 0 + 10·30·5 = 1500 | 1500 | 0 |
| 2 | [1, 2] | k=1: 0 + 0 + 30·5·60 = 9000 | 9000 | 1 |
| 3 | [0, 2] | k=0: 0 + 9000 + 10·30·60 = 27000; k=1: 1500 + 0 + 10·5·60 = 4500 | 4500 | 1 |
The final split[0][2] = 1 says the last multiplication is (A0 A1) × A2, which matches the hand calculation.
Checking Against Brute Force
When you write an interval DP, compare it against a direct recursive search on small inputs. The search below tries every split at every level with no memoization. It is exponential, but it finishes instantly for a handful of matrices, and it encodes the recurrence with no table-ordering logic that could go wrong.
def brute_force_chain(dims, i, j):
if i == j:
return 0
return min(
brute_force_chain(dims, i, k)
+ brute_force_chain(dims, k + 1, j)
+ dims[i] * dims[k + 1] * dims[j + 1]
for k in range(i, j)
)
dims = [30, 35, 15, 5, 10, 20, 25]
print(brute_force_chain(dims, 0, len(dims) - 2)) # 15125This six-matrix chain is the classic textbook instance. Running matrix_chain_order on the same dims should also give 15125. Random tests that compare both functions on chains of 1 to 8 matrices catch nearly every indexing bug.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using `n = len(dims)` | Index error, or the table has a phantom matrix | `n = len(dims) - 1` |
| Merge cost `dims[i] * dims[k] * dims[j]` | Wrong totals that are close to plausible | The shared dimension is `dims[k + 1]`; the right edge is `dims[j + 1]` |
| Leaving `dp[i][j] = 0` before the `k` loop | Every answer is 0 | Start from infinity |
| `k` ranging to `j` inclusive | Reads `dp[j + 1][j]`, an empty interval that is never set | `range(i, j)` |
| Filling rows `i` ascending, `j` ascending | Reads `dp[k + 1][j]` before it is computed | Loop by length, or loop `i` descending |
| Returning `dp[0][n]` | Index error | Answer is `dp[0][n - 1]` |
Edge Cases
- One matrix (
dimsof length 2): the length loop never runs, anddp[0][0] = 0is returned. That is correct, since nothing has to be multiplied. - Zero matrices (
dimsof length 0 or 1):nis 0 or negative, anddp[0][n - 1]fails. Guard against this explicitly if your input allows it. - Ties: several
kvalues can reach the same minimum. The strict<keeps the leftmost one. Any of them gives the optimal cost, but different tie-breaking produces different parenthesizations, so tests should compare costs and not strings. - Dimensions of 1: vectors in the chain make some splits nearly free. The recurrence handles this without special cases, and these inputs are good test cases because the optimal order is often unintuitive.
- Large values: Python integers do not overflow. In C++ or Java, use 64-bit integers, because products of three dimensions summed over many steps easily pass
2^31.
Cost of the Algorithm
The table has about n²/2 states, and each state tries up to n - 1 splits, so the running time is O(n³) and the space is O(n²). A later chapter on complexity counts this exactly. For chains of a few hundred matrices this is fast. The DP's own work is also tiny compared with the matrix multiplications it saves.
Exercise
For dims = [5, 10, 3, 12, 5], compute dp for every interval by hand and give the minimum cost and the value of split[0][3].
Show answer
The length-2 intervals are dp[0][1] = 5·10·3 = 150, dp[1][2] = 10·3·12 = 360, and dp[2][3] = 3·12·5 = 180. For length 3, dp[0][2] = min(0 + 360 + 5·10·12 = 960, 150 + 0 + 5·3·12 = 330) = 330, and dp[1][3] = min(0 + 180 + 10·3·5 = 330, 360 + 0 + 10·12·5 = 960) = 330. For dp[0][3], split k=0 gives 0 + 330 + 5·10·5 = 580, k=1 gives 150 + 180 + 5·3·5 = 405, and k=2 gives 330 + 0 + 5·12·5 = 630. The minimum is 405 with split[0][3] = 1, which is (A0 A1)(A2 A3).
Exercise
A colleague writes the merge cost as dims[i] dims[k] dims[j]. Using dims = [10, 30, 5, 60], what does their version compute for dp[0][1], and why is it wrong?
Show answer
Their version computes dims[0]·dims[0]·dims[1] = 10·10·30 = 3000 instead of 1500. The product A0..Ak has shape dims[i] × dims[k+1], and A(k+1)..Aj has shape dims[k+1] × dims[j+1]. The correct cost is therefore dims[i]·dims[k+1]·dims[j+1] = 10·30·5 = 1500. Their indices are shifted by one on the inner and right dimensions.
Exercise
Why is it safe to solve the left part Ai..Ak and the right part A(k+1)..Aj independently once k is fixed?
Show answer
The cost of the final multiplication depends only on the shapes of the two partial products, dims[i] × dims[k+1] and dims[k+1] × dims[j+1]. Those shapes are the same however each side is parenthesized. No choice made inside one side changes the cost of the other side or of the merge, so minimizing each side on its own minimizes the total for that k.