Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Matrix chain multiplication

Lesson · 11 min read · Dynamic programming · Matrix chain multiplication

Where to put the brackets in a product of matrices so it costs the fewest multiplications. Each interval tries every split point.

Why the order matters

Multiplying a p × q matrix by a q × r matrix costs p · q · r scalar multiplications. Matrix multiplication is associative, so a chain A·B·C can be computed as (A·B)·C or A·(B·C), and the costs can differ enormously. With A 10 × 30, B 30 × 5 and C 5 × 60:

  • (A·B)·C costs 10·30·5 + 10·5·60 = 1,500 + 3,000 = 4,500;
  • A·(B·C) costs 30·5·60 + 10·30·60 = 9,000 + 18,000 = 27,000.

The chain is given as a list of dimensions d: matrix i is d[i] × d[i + 1].

The interval recurrence with a split point

Recurrence

cost(i, j)

  1. fewest multiplications to compute matrices i..j =
  2. min over the last split k, i ≤ k < j, of cost(i, k) + cost(k + 1, j) + d[i] · d[k + 1] · d[j + 1].

base cases

  1. cost(i, i) = 0: a single matrix needs no work.

This "try every split, combine the two sides, pay for joining them" shape is the template for interval DP: burst balloons, merging stones, cutting a stick and optimal binary search trees all follow it.

A 10×30, B 30×5, C 5×60. Intervals by length; each tries every split point.

  1. Step 1 / 7
    ABCABC

    Base cases filled first.

  2. Step 2 / 7
    ABCA0BC

    A single matrix: 0.

  3. Step 3 / 7
    ABCA0B0C

    A single matrix: 0.

  4. Step 4 / 7
    ABCA0B0C0

    A single matrix: 0.

  5. Step 5 / 7
    ABCA01500B0C0

    AB: split after A: 1500. Best 1500.

  6. Step 6 / 7
    ABCA01500B09000C0

    BC: split after B: 9000. Best 9000.

  7. Step 7 / 7
    ABCA015004500B09000C0

    ABC: split after A: 27000; split after B: 4500. Best 4500. cost(A..C) = 4500, splitting after B: (A·B)·C.

Implementation

In six languages:

def matrix_chain(dims):
    n = len(dims) - 1                          # number of matrices
    cost = [[0] * n for _ in range(n)]         # cost[i][j]: matrices i..j
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            cost[i][j] = min(cost[i][k] + cost[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
                             for k in range(i, j))   # k: where the last multiplication splits
    return cost[0][n - 1]

The same code is the reference solution to The cheapest order to multiply matrices, where it is compiled and run against the tests in all six languages.

TimeO(n³)
SpaceO(n²)

n² intervals, up to n split points each. Recording the best split per interval lets you print the brackets.