Matrix Chain Multiplication solution explained

Matrix Chain Multiplication asks for the cheapest order in which to multiply a chain of matrices, counted in scalar multiplications. Let cost[i][j] be the cheapest way to multiply matrices i through j; try every split point k, add the two sides plus the cost of the final product, and keep the minimum. Filling the table by chain length takes O(n³) time and O(n²) space, and a second table of best splits lets you print the parenthesization.

By Published 8 min read

The problem

You have a chain of matrices A1, A2, ..., An that can be multiplied in sequence, which means the number of columns of each one equals the number of rows of the next. Their shapes come as one list dims of length n + 1, with Ai being dims[i − 1] rows by dims[i] columns. Matrix multiplication is associative, so any parenthesization gives the same product, but not the same amount of work: multiplying a p × q matrix by a q × r matrix takes p · q · r scalar multiplications. Return the smallest total over all orders, and be ready to say which order achieves it.

Dimension lists made up for this page
dimsMatricesCheapest orderCost
[2, 3, 4]2×3, 3×4Only one order24
[6, 2, 8, 3]6×2, 2×8, 8×3A1(A2A3)84
[4, 10, 3, 12, 20]4×10, 10×3, 3×12, 12×20(A1A2)(A3A4)1080
[8, 8]One 8×8 matrixNothing to multiply0
Dimension lists made up for this page. Scroll sideways on a small screen.

The second row shows why order matters. Multiplying (A1A2) first costs 6 · 2 · 8 = 96 and leaves a 6 × 8 matrix, then times A3 costs 6 · 8 · 3 = 144, for 240 total. Doing A2A3 first costs 2 · 8 · 3 = 48 and leaves a 2 × 3 matrix, then A1 times that costs 6 · 2 · 3 = 36, for 84. Same answer, under half the work.

This problem usually appears as a named dynamic programming exercise rather than a judge puzzle, so interviewers often state it loosely. Pin down the input format, whether they want only the cost or also the order, and whether a chain of one matrix is allowed (it costs zero).

Slow approach: recurse on the last multiplication

Whatever order you choose, there is one final multiplication that joins a left block A_i..A_k with a right block A_(k+1)..A_j. The left block ends up dims[i − 1] × dims[k] and the right block dims[k] × dims[j], so that last step costs dims[i − 1] · dims[k] · dims[j]. The best total for i..j is the minimum, over all k, of best(i, k) + best(k + 1, j) plus that final cost. Written directly, the recursion recomputes the same intervals many times and the number of calls grows exponentially.

def chain_cost_slow(dims):
    def best(i, j):  # cheapest way to multiply matrices i..j (1-based)
        if i == j:
            return 0
        return min(best(i, k) + best(k + 1, j) + dims[i - 1] * dims[k] * dims[j]
                   for k in range(i, j))

    return best(1, len(dims) - 1)
Direct recursion over split points: correct, exponential.

Main approach: interval dynamic programming

There are only about n²/2 distinct intervals (i, j), and each one depends only on shorter intervals inside it. So build a table cost[i][j] and fill it by length: all single matrices cost zero, then every interval of length 2, then 3, up to the full chain. When you reach an interval, every shorter interval it needs is already final. Each interval tries up to n − 1 split points, which gives O(n³) time.

A second table, split[i][j], records the k that gave the minimum. That costs nothing extra in time and lets you rebuild the order afterwards by recursing from split[1][n].

def chain_cost(dims):
    n = len(dims) - 1
    cost = [[0] * (n + 1) for _ in range(n + 1)]
    split = [[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
            cost[i][j] = float("inf")
            for k in range(i, j):
                trial = cost[i][k] + cost[k + 1][j] + dims[i - 1] * dims[k] * dims[j]
                if trial < cost[i][j]:
                    cost[i][j] = trial
                    split[i][j] = k
    return cost[1][n], split


def chain_order(split, i, j):
    if i == j:
        return "A" + str(i)
    k = split[i][j]
    return "(" + chain_order(split, i, k) + chain_order(split, k + 1, j) + ")"
Python: bottom-up by chain length, plus the split table for reconstruction.
function chainCost(dims) {
  const n = dims.length - 1;
  const cost = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
  for (let length = 2; length <= n; length++) {
    for (let i = 1; i + length - 1 <= n; i++) {
      const j = i + length - 1;
      cost[i][j] = Infinity;
      for (let k = i; k < j; k++) {
        const trial = cost[i][k] + cost[k + 1][j] + dims[i - 1] * dims[k] * dims[j];
        if (trial < cost[i][j]) cost[i][j] = trial;
      }
    }
  }
  return cost[1][n];
}
JavaScript: the cost table only, same loop order.

For dims = [6, 2, 8, 3], the length-2 intervals are cost[1][2] = 96 and cost[2][3] = 48. For the whole chain, k = 1 gives 0 + 48 + 6 · 2 · 3 = 84 and k = 2 gives 96 + 0 + 6 · 8 · 3 = 240, so cost[1][3] = 84 with split 1, and chain_order prints (A1(A2A3)).

Top-down is fine too

Adding a cache to the slow recursion (lru_cache on best(i, j)) gives the same O(n³) bound with less index bookkeeping. Many candidates find the memoized version easier to get right under pressure. The bottom-up table is worth knowing because interviewers sometimes ask for the fill order explicitly, and it avoids deep recursion on long chains.

Complexity

n matrices, dims of length n + 1
ApproachTimeExtra space
Recursion over split pointsExponentialO(n) stack
Memoized recursionO(n³)O(n²) cache plus O(n) stack
Bottom-up interval tableO(n³)O(n²), two tables if you keep splits
n matrices, dims of length n + 1. Scroll sideways on a small screen.

Faster special-purpose algorithms for this exact problem exist in the research literature, but they are long and intricate. In an interview, O(n³) is the expected bound; mentioning that it can be improved is enough.

Edge cases

  • One matrix (dims of length 2): cost 0, and the order is just A1.
  • Two matrices: one possible product, cost dims[0] · dims[1] · dims[2].
  • Dimensions of 1, such as [9, 1, 9, 1]: A1(A2A3) costs 18 while (A1A2)A3 costs 162, a good test that the min really compares every split.
  • Large dimensions in languages with fixed-size integers: a single product of three dimensions can overflow 32 bits, so use 64-bit totals.
  • An empty or one-element dims list is not a valid chain; decide whether to reject it.

Common mistakes

  • Using dims[i] · dims[k] · dims[j] instead of dims[i − 1] · dims[k] · dims[j]. With 1-based matrices, the rows of Ai are dims[i − 1].
  • Filling the table row by row from the top, so cost[k + 1][j] is read before it is computed. Fill by increasing length, or by i descending.
  • Greedy choices, like always multiplying the pair with the smallest product first. Small inputs quickly break it.
  • Forgetting to initialize cost[i][j] to infinity before taking the minimum, so the zero from the table wins.
  • Returning only the cost when the interviewer asked for the order. Keep the split table from the start.

Explaining it in the room

Fictional example

From recursion to a table
Candidate
Any order has a last multiplication that splits the chain at some k. The two sides are independent subproblems, and the final step costs dims[i − 1] times dims[k] times dims[j].
Candidate
So cost of i to j is the min over k of the two sides plus that product. There are O(n²) intervals, each with O(n) splits, so O(n³) time.
Candidate
I'll fill by interval length so the shorter pieces are ready, and keep the best k per interval so I can print the parenthesization at the end.

Connected problems

Different Ways to Add Parentheses explores the same space of groupings but lists every result instead of keeping a single best one per interval. For another cost-minimizing problem with a very different shape, Optimize Water Distribution in a Village solves its optimization greedily with a spanning tree. More dynamic programming and divide-and-conquer topics are on the algorithm interview questions page.

Natively as a practice partner

Interval DP is mostly about stating the state and the fill order clearly. While you practice, Natively can read the problem from a screenshot and suggest an approach to set beside your own, and it can transcribe a mock round on your computer so you can check that you explained why the table is filled by length. Read about an AI interview assistant for the details.

Questions people ask

What is the recurrence for Matrix Chain Multiplication?

cost[i][j] = min over k from i to j - 1 of cost[i][k] + cost[k + 1][j] + dims[i - 1] × dims[k] × dims[j], with cost[i][i] = 0. Matrix i has shape dims[i - 1] × dims[i].

What is the time complexity of the DP solution?

O(n³) time and O(n²) space for n matrices: there are O(n²) intervals and each one tries O(n) split points.

Why fill the table by chain length?

Each interval depends only on shorter intervals inside it. Filling by increasing length guarantees those values are final before they are read.

How do you print the optimal parenthesization?

Record the best split k for each interval in a second table. Then recurse from the full chain: wrap the order for i..k and the order for k + 1..j in parentheses.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP