Algorithms · Visualized

DP: Matrix Chain Multiplication

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Given a sequence of matrices, finds the optimal order to multiply them together to minimize the total number of scalar multiplications (matrix multiplication is associative, so different groupings give the same result but very different costs). Time: O(n³) average, O(n³), where n is the number of matrices worst; space: O(n²) — the dp table.

Big-O: The most-asked interview category — 35 classics here.

Matrix Chain Multiplication

Dynamic Programming

Given a sequence of matrices, finds the optimal order to multiply them together to minimize the total number of scalar multiplications (matrix multiplication is associative, so different groupings give the same result but very different costs). dp[i][j] represents the minimum cost to multiply the chain of matrices from i to j, built by trying every possible 'split point' where the chain could be divided.

How Matrix Chain Multiplication Works

  1. Represent the matrix dimensions as an array p, where matrix i has dimensions p[i-1] × p[i]. Define dp[i][j] as the minimum multiplication cost for multiplying matrices i through j together.
  2. Base case: dp[i][i] = 0 (a single matrix needs no multiplication).
  3. For each chain length from 2 up to the total number of matrices, and for each valid starting point i, try every possible split point k between i and j.
  4. For each split k, the cost is dp[i][k] + dp[k+1][j] + (p[i-1] × p[k] × p[j]) — the cost of solving each half plus the cost of multiplying the two resulting matrices together.
  5. Set dp[i][j] to the minimum cost found across all split points; continue until dp[1][n] (the full chain) is computed, which is the final minimum cost.

Matrix Chain Multiplication Worked Example

Input: [40, 20, 30, 10, 30]

This represents 4 matrices: A(40×20), B(20×30), C(30×10), D(10×30). Trying different groupings: ((AB)C)D vs A((BC)D) vs (AB)(CD), etc., each split point cost is computed via the recurrence. Working through all split combinations, the optimal grouping achieves a minimum cost of 26,000 scalar multiplications (specific optimal parenthesization: A((BC)D)).

DP: Matrix Chain MultiplicationO(n³)
Optimal parenthesization.
40
0
20
1
30
2
10
3
30
4
0123
00000
10000
20000
30000
Step 1 / 8
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Matrix Chain Multiplication: dp[i][j] = min scalar multiplications for matrices i..j.
Python · Dynamic Programming Algorithms in Code
def matrix_chain(dims):
    # dims[i] x dims[i+1] are the matrix dimensions
    n = len(dims) - 1
    dp = [[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] = float('inf')
            for k in range(i, j):
                cost = (dp[i][k] + dp[k + 1][j]
                        + dims[i] * dims[k + 1] * dims[j + 1])
                dp[i][j] = min(dp[i][j], cost)
    return dp[0][n - 1]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Matrix Chain Multiplication Time & Space Complexity

BestO(n³)
AverageO(n³)
WorstO(n³), where n is the number of matrices
SpaceO(n²) — the dp table

When to Use Matrix Chain Multiplication

  • Query optimization in database systems (choosing the optimal join order), and compiler optimization for expression evaluation order.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.