GeeksforGeeks Hard

Matrix Chain Multiplication

Matrix Chain Multiplication is a GFG problem (Hard). You are given an array arr of n + 1 numbers describing n matrices: matrix i has arr[i-1] rows and arr[i] columns. Return the fewest scalar multiplications needed to multiply the whole chain.

  • Multiplying a p × q matrix by a q × r matrix costs p · q · r multiplications and gives a p × r matrix.
  • You may choose any bracketing, but not reorder the matrices.
  • A single matrix needs no work, so arr = [3, 4] gives 0.
Constraints
  • 2 <= arr.size() <= 100
  • 1 <= arr[i] <= 200
dpinterval-dp
Open on GeeksforGeeks ↗
02

Intuition

Every bracketing gives the same product, because matrix multiplication is associative, but the costs differ a lot. For 2×1, 1×3, 3×4, multiplying the left pair first costs 30, the right pair first only 20.

Trying every bracketing is exponential. Instead, ask which multiplication happens last. If the last one joins matrices i..k with k+1..j, both sides were already reduced to single matrices, independently of each other, and the final step costs arr[i-1] · arr[k] · arr[j]. So the best cost for a chain is the cheapest choice of k of: best left side + best right side + that final cost.

03

Approach

1

Define one cell per chain

Let dp[i][j] be the fewest multiplications to turn matrices i through j into one matrix (1-indexed). A chain of one matrix costs nothing, so dp[i][i] = 0.

2

Try every split point

For i < j, the last multiplication can sit after any k from i to j - 1:

dp[i][j] = min over k of dp[i][k] + dp[k+1][j] + arr[i-1] · arr[k] · arr[j].

The left result is arr[i-1] × arr[k] and the right is arr[k] × arr[j], which is where the three factors come from.

3

Fill by chain length

Both halves are shorter than the chain being solved, so fill all chains of length 2 first, then length 3, and so on up to n. The answer is dp[1][n].

4

Recover the brackets

Store the winning k for each cell in a second table. To print the order, split the whole chain at its k, wrap each side in brackets, and repeat on each side until a side is a single matrix.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def matrixMultiplication(self, arr):
▶3 n = len(arr) - 1
▶4 dp = [[0] * (n + 1) for _ in range(n + 1)]
▶5 for length in range(2, n + 1):
▶6 for i in range(1, n - length + 2):
▶7 j = i + length - 1
▶8 dp[i][j] = min(
▶9 dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]
▶10 for k in range(i, j)
▶11 )
▶12 return dp[1][n]
matricesA12×1A21×3A33×4this splitnot startedbest cost per chainA1–A2A2–A3A1–A33 matrices, every chain still unpriced
matrices3
chains to price3
Each matrix is drawn to scale: height is its rows, width its columns. Neighbours always fit, because each matrix has as many columns as the next has rows. A single matrix costs nothing, so only chains of two or more need a price, shortest first.
matricesA12×1A21×3A33×4this split0A1+0A2+6last multiply=6best yetbest cost per chain6A1–A2A2–A3A1–A3A1 × A2 costs 6
chainA1–A2
best so far6
Split A1–A2 after A1. The left side becomes one 2×1 matrix for 0, the right side one 1×3 matrix for 0, and joining them costs 2 × 1 × 3 = 6. 6 is the cheapest way found so far for this chain.
matricesA12×1A21×3A33×4this split0A2+0A3+12last multiply=12best yetbest cost per chain6A1–A212A2–A3A1–A3A2 × A3 costs 12
chainA2–A3
best so far12
Split A2–A3 after A2. The left side becomes one 1×3 matrix for 0, the right side one 3×4 matrix for 0, and joining them costs 1 × 3 × 4 = 12. 12 is the cheapest way found so far for this chain.
matricesA12×1A21×3A33×4this split0A1+12A2–A3+8last multiply=20best yetbest cost per chain6A1–A212A2–A320A1–A3last multiply after A1 → 20
chainA1–A3
best so far20
Split A1–A3 after A1. The left side becomes one 2×1 matrix for 0, the right side one 1×4 matrix for 12, and joining them costs 2 × 1 × 4 = 8. 20 is the cheapest way found so far for this chain.
matricesA12×1A21×3A33×4this split6A1–A2+0A3+24last multiply=30worsebest cost per chain6A1–A212A2–A320A1–A3last multiply after A2 → 30, no better than 20
chainA1–A3
best so far20
Split A1–A3 after A2. The left side becomes one 2×3 matrix for 6, the right side one 3×4 matrix for 0, and joining them costs 2 × 3 × 4 = 24. That totals 30, which does not beat 20, so the stored best stays.
matricesA12×1A21×3A33×4best orderA1 × (A2 × A3)best cost per chain6A1–A212A2–A320A1–A3answer: 20
answer20chain A1–A3
orderA1 × (A2 × A3)
Answer 20. The whole chain's cell holds the minimum. Remembering which split won in each chain gives the brackets: split the whole chain at its winning point, then split each side the same way.
05

Recursion with a memo

solve(i, j) returns the cheapest cost for matrices i..j. It tries every split k and caches the result, so each of the O(n²) chains is solved once. Without the cache the same chains are solved again and again and the running time is exponential.

▶1from functools import cache
▶2 
▶3 
▶4class Solution:
▶5 def matrixMultiplication(self, arr):
▶6 @cache
▶7 def solve(i, j):
▶8 if i == j:
▶9 return 0
▶10 return min(
▶11 solve(i, k) + solve(k + 1, j) + arr[i - 1] * arr[k] * arr[j]
▶12 for k in range(i, j)
▶13 )
▶14 
▶15 return solve(1, len(arr) - 1)
06

Common pitfalls

Filling row by row instead of by length

✗ Wrong
for i in range(1, n + 1):
    for j in range(i + 1, n + 1):
✓ Right
for length in range(2, n + 1):
    for i in range(1, n - length + 2):
        j = i + length - 1

dp[i][j] reads dp[k+1][j], a later row that row-by-row order has not filled, so it reads 0. On [1, 2, 3, 4, 3] that returns 6 instead of 30.

Using arr[i] for the left side's rows

✗ Wrong
arr[i] * arr[k] * arr[j]
✓ Right
arr[i - 1] * arr[k] * arr[j]

Matrix i is arr[i-1] × arr[i], so the joined left side has arr[i-1] rows. On [2, 1, 3, 4] the wrong index returns 15 instead of 20.

Letting k reach j

✗ Wrong
for k in range(i, j + 1)
✓ Right
for k in range(i, j)

With k = j the right side k+1..j is empty. It reads dp[j+1][j], which is 0 or out of range, and invents a split that does not exist.

07

Complexity

Time
O(n³)
Space
O(n²)
About n²/2 chains, each trying up to n split points. With n ≤ 99 matrices that is under a million steps.
08

Matrix Chain Multiplication FAQ

Why not just multiply the cheapest pair first?

Because the cheap step can create an expensive matrix. With arr = [5, 1, 10, 10] the cheapest pair is the first one (50), but it leaves a 5 × 10 matrix and the next step costs 500, for 550 in total. Multiplying the right pair first costs 100 + 50 = 150. Only comparing every last split is guaranteed to find the minimum.

Is there something faster than O(n³)?

Yes. Hu and Shing (1981) found an O(n log n) matrix chain multiplication algorithm by turning the matrix chain into a polygon and cutting it into triangles. It is far longer to write, and the cubic DP is what interviews expect.

What other problems use the same split pattern?

Any problem where a range is solved by choosing one split or one last action inside it: Burst Balloons, minimum cost to cut a stick, and palindrome partitioning all fill a range table the same way.