Sub topic 13
Matrix chain multiplication
This chapter assumes you know Big-O notation, can read Python, and have seen the 0/1 knapsack and LCS tables. The new idea here is that the subproblems are intervals of a sequence, not prefixes.
The problem
Matrix multiplication is associative, so the product A1·A2·…·An gives the same result under any parenthesization. The cost does not stay the same. Multiplying a p×q matrix by a q×r matrix takes p·q·r scalar multiplications, and different parenthesizations can differ by orders of magnitude.
The task is to find the parenthesization with the fewest scalar multiplications. The task is not to multiply the matrices.
Matrix Ai has dimensions p[i-1] × p[i]. A chain of n matrices is therefore described by n+1 numbers p[0..n].
For p = [10, 30, 5, 60], the matrices are A1 (10×30), A2 (30×5) and A3 (5×60):
- (A1A2)A3 costs 10·30·5 + 10·5·60 = 1500 + 3000 = 4500.
- A1(A2A3) costs 30·5·60 + 10·30·60 = 9000 + 18000 = 27000.
Why brute force and greedy fail
The number of parenthesizations of n matrices is the Catalan number C(n-1), which grows exponentially. Enumerating them is not feasible.
No simple greedy rule works either, such as multiplying the cheapest adjacent pair first. The best last split depends on the whole interval, so the problem needs dynamic programming.
Recurrence
Let m[i][j] be the minimum cost of computing Ai…Aj. The outermost multiplication splits the chain at some k, with i ≤ k < j. The left part costs m[i][k], the right part costs m[k+1][j], and joining a p[i-1]×p[k] result with a p[k]×p[j] result costs p[i-1]·p[k]·p[j].
- Base case: m[i][i] = 0, because a single matrix needs no multiplication.
- Recurrence: m[i][j] = min over k from i to j-1 of ( m[i][k] + m[k+1][j] + p[i-1]·p[k]·p[j] ).
Optimal substructure holds because each side of an optimal split must itself be optimal. Overlapping subproblems arise because the same interval appears under many different splits.
Filling order
m[i][j] depends on shorter intervals, so fill the table by increasing chain length, not row by row. Length 1 is the diagonal of zeros. Then compute all intervals of length 2, then 3, and so on up to n.
Implementation
The array s stores the best split point, which lets you rebuild the parenthesization.
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(2, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
m[i][j] = float('inf')
for k in range(i, j):
cost = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]
if cost < m[i][j]:
m[i][j] = cost
s[i][j] = k
return m, s
def parens(s, i, j):
if i == j:
return f"A{i}"
k = s[i][j]
return "(" + parens(s, i, k) + parens(s, k + 1, j) + ")"
p = [40, 20, 30, 10, 30]
m, s = matrix_chain_order(p)
print(m[1][4]) # 26000
print(parens(s, 1, 4)) # ((A1(A2A3))A4)Hand trace
This is the kind of trace GATE expects. The chain is p = [40, 20, 30, 10, 30].
| Interval | Computation | m | Best k |
|---|---|---|---|
| 1..2 | 40·20·30 | 24000 | 1 |
| 2..3 | 20·30·10 | 6000 | 2 |
| 3..4 | 30·10·30 | 9000 | 3 |
| 1..3 | k=1: 0 + 6000 + 40·20·10 = 14000. k=2: 24000 + 0 + 40·30·10 = 36000 | 14000 | 1 |
| 2..4 | k=2: 0 + 9000 + 20·30·30 = 27000. k=3: 6000 + 0 + 20·10·30 = 12000 | 12000 | 3 |
| 1..4 | k=1: 0 + 12000 + 40·20·30 = 36000. k=2: 24000 + 9000 + 40·30·30 = 69000. k=3: 14000 + 0 + 40·10·30 = 26000 | 26000 | 3 |
Complexity
- The table has n(n+1)/2 cells, so there are Θ(n²) subproblems. Only the cells with i < j, n(n-1)/2 of them, need real work.
- Each cell tries up to n-1 splits, so the time is Θ(n³).
- The m and s tables take Θ(n²) space.
- A top-down memoized version has the same bounds. It computes only the intervals it needs, but it adds recursion overhead.
Common errors
- Off-by-one in dimensions. A chain of n matrices has a dimension array of length n+1. Ai is p[i-1]×p[i], not p[i]×p[i+1].
- Wrong split range. The k loop runs from i to j-1. Letting k reach j makes m[k+1][j] refer to an empty interval.
- Wrong loop order. Iterating i then j in plain nested loops reads cells that are not computed yet. Iterate by chain length.
- Confusing the cost with the product. The answer counts scalar multiplications. The shape of the final matrix is always p[0]×p[n].
Exercise
For p = [5, 10, 20, 5], find the minimum number of scalar multiplications for A1A2A3 and the optimal parenthesization.
Show answer
(A1A2)A3 costs 5·10·20 + 5·20·5 = 1000 + 500 = 1500. A1(A2A3) costs 10·20·5 + 5·10·5 = 1000 + 250 = 1250. The minimum is 1250, with parenthesization A1(A2A3), which is split k=1.
Exercise
For a chain of 6 matrices, how many cells m[i][j] with i < j must be computed, and what is the time complexity in terms of n?
Show answer
There are n(n-1)/2 = 15 such cells. Each tries up to n-1 split points, so the total time is Θ(n³) and the space is Θ(n²).