AlgoTales · Roadmap

Matrix chain multiplication

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Matrix chain multiplication finds the cheapest order in which to multiply a series of grids of numbers. The final result is the same whatever the order, but the work done is not. It teaches you to choose the best place to split a chain.

Practical use cases

  • Web app: Ordering joins in a heavy report. A reporting page joins five large tables, and the final result is the same in any order, but joining the big ones first made the report take 30 seconds. Checking the cost of each possible first split and remembering the best shows that joining the small tables first takes 2 seconds. The same reasoning is what query planners use.
  • Web app: Image filter pipeline. A photo-editing page applies several transformations to an image, each represented as a grid of numbers. Combining the small ones first and the large one last makes the page respond in under a second instead of several. The saved time is repeated every time a user clicks Apply, so the editor feels light even on a modest laptop.
  • System: Graphics, machine learning and databases. Graphics engines and machine learning libraries multiply long chains of matrices and pick the order that does the least arithmetic. Databases choose the order of joins similarly.

The story: Which Bracket First?

Mrs. Sharma gave Aarav a worksheet: multiply four rectangular grids of numbers, A, B, C and D. Multiplying two grids is allowed only if the width of the first equals the height of the second, and the work needed is the number of little multiplications: height × shared size × width. The strange part: the final answer is the same whichever pair you do first, but the work is very different.

Aarav tried (A × B) first, then C, then D. Tiring. Zoya tried (C × D) first and got through in far fewer steps. "Order matters!" she said. With four grids there are five different bracket styles; with twenty grids there are millions. Time to be clever.

Mira said, "Think about the last multiplication. It joins a left block and a right block. Try every place to cut the chain, add the best cost of the left block, the best cost of the right block and the cost of joining them, and take the cheapest cut." Small chains first, then longer ones. The cheapest total came to 26000. This is Matrix Chain Multiplication, the original partition DP problem. We do not multiply anything here; we only find the best order.

How to spot this problem, and where you need it

A chain of operations gives the same final answer in any grouping, yet some groupings are far more expensive than others, and you want the cheapest.

Signs you need it

  • The operation is associative, meaning (A then B) then C equals A then (B then C), but the sizes of the pieces differ a lot.
  • Changing the order in which you join, multiply or combine things makes the same job take seconds or minutes.
  • The problem says "minimum number of multiplications" or "best way to parenthesise".

Where to use it in a project

  • Choosing the order of table joins or merges in report and analytics code.
  • Ordering transformations in graphics, data-science or machine-learning pipelines.

The solution

Define cost(i, j) as the least work to combine items i through j. For each range, try every split point k: the cost is cost(i, k) plus cost(k+1, j) plus the cost of the final combine, which depends on the sizes. Keep the smallest. Fill the table for short ranges first, then longer ones, and read the whole chain's cost from the corner. Remember the best k to rebuild the order.

Payoff: Before: a report taking 30 seconds with a bad join order. After: the best order found in milliseconds, cutting it to about 2 seconds.

Explain it like I am 8

Imagine folding four blankets. The final folded size is always the same, but the number of folds you do can change depending on which pair you fold first. You try every first cut, remember the best way to fold each short pile and combine them.

How it works, step by step

  1. Write the sizes as one list d: matrix i has shape d[i-1] × d[i]. Four matrices need 5 numbers.
  2. One matrix costs 0. Fill longer chains next: 2, then 3, then 4 matrices.
  3. For the chain i..j try each cut k: cost = dp[i][k] + dp[k+1][j] + d[i-1]·d[k]·d[j].
  4. Keep the smallest cost as dp[i][j] (and remember the cut, if you need to print the brackets).
  5. The answer is dp[1][n], the chain of all matrices.

The code in four languages

PHP

<?php
// d[i-1] x d[i] is the shape of matrix i. Returns the fewest scalar multiplications.
function matrixChain(array $d): int {
    $n = count($d) - 1;                                  // number of matrices
    $dp = array_fill(1, $n, array_fill(1, $n, 0));       // dp[i][j]: cheapest cost of chain i..j
    for ($len = 2; $len <= $n; $len++) {                 // chain length, small to big
        for ($i = 1; $i + $len - 1 <= $n; $i++) {
            $j = $i + $len - 1;
            $dp[$i][$j] = PHP_INT_MAX;
            for ($k = $i; $k < $j; $k++) {               // try every place for the last multiplication
                $cost = $dp[$i][$k] + $dp[$k + 1][$j] + $d[$i - 1] * $d[$k] * $d[$j];
                if ($cost < $dp[$i][$j]) $dp[$i][$j] = $cost;
            }
        }
    }
    return $dp[1][$n];
}
echo matrixChain([40, 20, 30, 10, 30]), "\n";           // 26000
echo matrixChain([10, 30, 5, 60]), "\n";                // 4500

JavaScript

// d[i-1] x d[i] is the shape of matrix i. Returns the fewest scalar multiplications.
function matrixChain(d) {
  const n = d.length - 1;                                // number of matrices
  const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0)); // dp[i][j]: chain i..j
  for (let len = 2; len <= n; len++) {                   // chain length, small to big
    for (let i = 1; i + len - 1 <= n; i++) {
      const j = i + len - 1;
      dp[i][j] = Infinity;
      for (let k = i; k < j; k++) {                      // try every place for the last multiplication
        const cost = dp[i][k] + dp[k + 1][j] + d[i - 1] * d[k] * d[j];
        if (cost < dp[i][j]) dp[i][j] = cost;
      }
    }
  }
  return dp[1][n];
}
console.log(matrixChain([40, 20, 30, 10, 30]));          // 26000
console.log(matrixChain([10, 30, 5, 60]));               // 4500

Java

public class Main {
    // d[i-1] x d[i] is the shape of matrix i. Returns the fewest scalar multiplications.
    static int matrixChain(int[] d) {
        int n = d.length - 1;                                    // number of matrices
        int[][] dp = new int[n + 1][n + 1];                      // dp[i][j]: cheapest cost of chain i..j
        for (int len = 2; len <= n; len++) {                     // chain length, small to big
            for (int i = 1; i + len - 1 <= n; i++) {
                int j = i + len - 1;
                dp[i][j] = Integer.MAX_VALUE;
                for (int k = i; k < j; k++) {                    // try every place for the last multiplication
                    int cost = dp[i][k] + dp[k + 1][j] + d[i - 1] * d[k] * d[j];
                    if (cost < dp[i][j]) dp[i][j] = cost;
                }
            }
        }
        return dp[1][n];
    }

    public static void main(String[] args) {
        System.out.println(matrixChain(new int[]{40, 20, 30, 10, 30}));   // 26000
        System.out.println(matrixChain(new int[]{10, 30, 5, 60}));        // 4500
    }
}

Go

package main

import (
	"fmt"
	"math"
)

// d[i-1] x d[i] is the shape of matrix i. Returns the fewest scalar multiplications.
func matrixChain(d []int) int {
	n := len(d) - 1          // number of matrices
	dp := make([][]int, n+1) // dp[i][j]: cheapest cost of chain i..j
	for i := range dp {
		dp[i] = make([]int, n+1)
	}
	for length := 2; length <= n; length++ { // chain length, small to big
		for i := 1; i+length-1 <= n; i++ {
			j := i + length - 1
			dp[i][j] = math.MaxInt
			for k := i; k < j; k++ { // try every place for the last multiplication
				cost := dp[i][k] + dp[k+1][j] + d[i-1]*d[k]*d[j]
				if cost < dp[i][j] {
					dp[i][j] = cost
				}
			}
		}
	}
	return dp[1][n]
}

func main() {
	fmt.Println(matrixChain([]int{40, 20, 30, 10, 30})) // 26000
	fmt.Println(matrixChain([]int{10, 30, 5, 60}))      // 4500
}

Time: O(n³) · Extra space: O(n²). n² chains, each trying up to n cut places. Fine for a few hundred matrices, and the brute force is exponential.

Watch out for

  • Believing the order of multiplying does not matter for the cost. The result is the same, the work is not.
  • Filling by row order. Longer chains need shorter ones first, so loop by chain length.
  • Getting the shapes off by one: matrix i is d[i-1] by d[i].

Quick check

  1. What does each cell dp[i][j] store?
    • The shape of the result
    • The cheapest cost to multiply matrices i to j
    • The number of matrices
  2. For a chain, what do we try?
    • Every place to cut it in two
    • Only the middle
    • Only the first matrix
  3. Why does the order of multiplication matter for cost?
    • It changes the answer
    • It changes how many small multiplications are needed
    • It does not matter