Minimum Matrix Chain Multiplication Cost

Hard · Coding & Algorithms · Data Scientist · Technical Screen

Problem Statement

Given an integer list dimensions of length L, consider an ordered chain of L - 1 compatible matrices M_0, M_1, ..., M_{L-2} where matrix M_i has dimensions[i] rows and dimensions[i + 1] columns.

Multiplying a matrix of shape a x b by a matrix of shape b x c yields a matrix of shape a x c and requires a * b * c scalar multiplications. Because matrix multiplication is associative, you may parenthesize adjacent products in any valid order without altering the final result, though the total arithmetic work depends heavily on the chosen order.

Implement minimum_matrix_chain_cost(dimensions) to return the smallest total number of scalar multiplications needed to evaluate the product M_0 * M_1 * ... * M_{L-2}. When dimensions has only two elements, the chain contains just a single matrix and requires 0 multiplications.

def minimum_matrix_chain_cost(dimensions: List[int]) -> int:

Examples

Example 1

  • Input: dimensions = [4, 20, 3, 10]
  • Output: 360
  • Explanation: The list defines three matrices: M_0 (4 x 20), M_1 (20 x 3), and M_2 (3 x 10).
    • Evaluating (M_0 * M_1) * M_2 first forms a 4 x 3 intermediate matrix for 4 * 20 * 3 = 240 operations, then multiplies (4 x 3) by (3 x 10) for 4 * 3 * 10 = 120 operations, totaling 240 + 120 = 360.
    • Evaluating M_0 * (M_1 * M_2) costs (20 * 3 * 10) + (4 * 20 * 10) = 600 + 800 = 1400. The smaller total is 360.

Example 2

  • Input: dimensions = [12, 3, 8, 2]
  • Output: 120
  • Explanation: Here M_0 is 12 x 3, M_1 is 3 x 8, and M_2 is 8 x 2.
    • Evaluating (M_0 * M_1) * M_2 costs (12 * 3 * 8) + (12 * 8 * 2) = 288 + 192 = 480.
    • Evaluating M_0 * (M_1 * M_2) first collapses the 8-wide inner dimension into a 3 x 2 product for 3 * 8 * 2 = 48 operations, followed by 12 * 3 * 2 = 72 operations, totaling 48 + 72 = 120.

Constraints

  • 2 <= len(dimensions) <= 500
  • 1 <= dimensions[i] <= 1000

Step-by-step walkthrough

  1. Understand how matrix shapes and parenthesization change the cost

    A list dimensions of length L describes num_matrices = L - 1 matrices in a fixed left-to-right lineup. Using 0-based indexing, matrix A_m has dimensions[m] rows and dimensions[m + 1] columns, so adjacent matrices always share their inner dimension.

    Matrix multiplication is associative — (A_0 * A_1) * A_2 and A_0 * (A_1 * A_2) produce the exact same output matrix — yet the arithmetic work can differ dramatically! Look at Example 1 (dimensions = [4, 20, 3, 10], three matrices):

    Matrices:   A_0 (4 x 20)     A_1 (20 x 3)     A_2 (3 x 10)
    
    Order 1: (A_0 * A_1) * A_2
      1. A_0 * A_1  ->  (4 x 20) * (20 x 3) = 4 x 3   costs  4 * 20 *  3 =   240
      2. result * A_2 -> (4 x 3) * (3 x 10) = 4 x 10  costs  4 *  3 * 10 =   120
                                                                Total    =   360
    
    Order 2: A_0 * (A_1 * A_2)
      1. A_1 * A_2  ->  (20 x 3) * (3 x 10) = 20 x 10 costs 20 *  3 * 10 =   600
      2. A_0 * result -> (4 x 20) * (20 x 10) = 4 x 10 costs 4 * 20 * 10 =   800
                                                                Total    = 1,400
    

    Notice that greedy rules like "always multiply the cheapest adjacent pair first" also fail: on dimensions = [5, 9, 4, 4], the cheapest first pair is (9 x 4) * (4 x 4) = 144, leading to 144 + (5 * 9 * 4) = 324, whereas multiplying (5 x 9) * (9 x 4) = 180 first eliminates the large 9 early for 180 + (5 * 4 * 4) = 260. And if len(dimensions) == 2, there is only 1 matrix and zero multiplications, so the cost is 0.

  2. Think backward from the very last multiplication

    Instead of guessing which pair to multiply first, focus on the very last multiplication needed to finish any contiguous subchain A_left ... A_right (left < right).

    That final multiplication must join two already-computed halves at some index split (left <= split < right):

      ( A_left * ... * A_split )   x   ( A_{split+1} * ... * A_right )
      \________________________/       \_____________________________/
       outer_rows x shared_dim           shared_dim x outer_cols
       = dimensions[left]                = dimensions[split + 1]
         x dimensions[split + 1]           x dimensions[right + 1]
    

    Check the three dimensions carefully:

    • No matter what order we used inside the left half A_left ... A_split, its resulting matrix always has dimensions[left] rows and dimensions[split + 1] columns.
    • No matter what order we used inside the right half A_{split+1} ... A_right, its resulting matrix always has dimensions[split + 1] rows and dimensions[right + 1] columns.
    • Therefore, multiplying those two halves together always costs dimensions[left] * dimensions[split + 1] * dimensions[right + 1]!

    Because the cost of the final step depends only on the fixed outer shapes of the two halves and not on how either half was computed internally, the best way to compute A_left ... A_right via split must use the best way to compute left..split plus the best way to compute (split + 1)..right.

  3. Why plain recursion explodes—and how a 2D table fixes it

    If we write a plain recursive function min_cost(left, right) that tries every split from left to right - 1, it returns the right answer on tiny inputs:

    def brute_min_cost(dimensions: List[int], left: int, right: int) -> int:
        if left == right:
            return 0
        best_cost = None
        for split in range(left, right):
            merge_cost = dimensions[left] * dimensions[split + 1] * dimensions[right + 1]
            candidate = (
                brute_min_cost(dimensions, left, split)
                + brute_min_cost(dimensions, split + 1, right)
                + merge_cost
            )
            if best_cost is None or candidate < best_cost:
                best_cost = candidate
        return best_cost
    

    Why is this far too slow for up to 499 matrices? Because the exact same subchains get solved over and over ((1, 2) is recomputed inside (0, 2), (1, 3), (0, 3), ...), making 3^(n - 1) total calls!

    Yet there are only n * (n + 1) / 2 distinct pairs (left, right) with 0 <= left <= right < n. By storing each subchain's minimum cost once in a 2D table dp[left][right] (interval dynamic programming), we never solve any subchain twice:

    • Base case (chain_len = 1): dp[i][i] = 0 for every single matrix A_i.
    • Transition (left < right): dp[left][right] = min over split in [left .. right - 1] of (dp[left][split] + dp[split + 1][right] + dimensions[left] * dimensions[split + 1] * dimensions[right + 1]).
  4. Why we must fill the table by increasing chain length

    Look at which cells dp[left][right] reads inside the dp grid:

    • dp[left][split] sits to the left in the same row (split < right, shorter interval).
    • dp[split + 1][right] sits below in the same column (split + 1 > left, shorter interval).
             right ->
    left   [  0     len=2   len=3 ]
      |    [  .       0     len=2 ]   To compute dp[0][2] (len=3), we read:
      v    [  .       .       0   ]     - left in row 0:  dp[0][0], dp[0][1]
                                        - down in col 2:  dp[1][2], dp[2][2]
    

    If you looped left from 0 downward to n - 1, dp[0][2] would try to read dp[1][2] before row 1 had been computed! Looping on chain_len = 2, 3, ..., num_matrices fills one diagonal at a time outward from the main diagonal of zeros, guaranteeing every shorter subchain is already ready:

    num_matrices = len(dimensions) - 1
    dp: list[list[int]] = [[0] * num_matrices for _ in range(num_matrices)]
    
    for chain_len in range(2, num_matrices + 1):
        for left in range(0, num_matrices - chain_len + 1):
            right = left + chain_len - 1
            outer_rows = dimensions[left]
            outer_cols = dimensions[right + 1]
            best_cost: Optional[int] = None
    
            for split in range(left, right):
                shared_dim = dimensions[split + 1]
                merge_cost = outer_rows * shared_dim * outer_cols
                candidate_cost = dp[left][split] + dp[split + 1][right] + merge_cost
    
                if best_cost is None or candidate_cost < best_cost:
                    best_cost = candidate_cost
    
            dp[left][right] = best_cost
    

    Notice we initialize best_cost = None rather than 0 (otherwise 0 would falsely beat every positive multiplication cost!).

  5. Trace Example 1 diagonal by diagonal

    Let's trace dimensions = [4, 20, 3, 10], which has num_matrices = 3 (A_0: 4x20, A_1: 20x3, A_2: 3x10):

    1. Diagonal (chain_len = 1, initialized to 0):
       dp[0][0] = 0,  dp[1][1] = 0,  dp[2][2] = 0
    
    2. Pairs (chain_len = 2):
       dp[0][1] (split=0): dp[0][0] + dp[1][1] +  4 * 20 *  3 = 0 + 0 + 240 = 240
       dp[1][2] (split=1): dp[1][1] + dp[2][2] + 20 *  3 * 10 = 0 + 0 + 600 = 600
    
    3. Full chain (chain_len = 3, left = 0, right = 2):
       split = 0 -> A_0 * (A_1..A_2): dp[0][0] + dp[1][2] + 4 * 20 * 10 = 0 + 600 + 800 = 1400
       split = 1 -> (A_0..A_1) * A_2: dp[0][1] + dp[2][2] + 4 *  3 * 10 = 240 + 0 + 120 =  360  <-- min!
    
    Final dp table:
             right=0  right=1  right=2
    left=0 [    0,      240,     360 ]  <-- return dp[0][2] = 360
    left=1 [    0,        0,     600 ]
    left=2 [    0,        0,       0 ]
    
  6. Complete solution

    Putting everything together gives the complete O(n^3) time, O(n^2) space solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def minimum_matrix_chain_cost(dimensions: List[int]) -> int:
        # A list of L dimensions defines (L - 1) matrices:
        # Matrix idx (0-based) has shape dimensions[idx] x dimensions[idx + 1].
        num_matrices = len(dimensions) - 1
    
        # dp[left][right] = minimum scalar multiplications to compute A_left * ... * A_right.
        # Base case: a single matrix (left == right) needs 0 multiplications, so diagonal stays 0.
        dp: list[list[int]] = [[0] * num_matrices for _ in range(num_matrices)]
    
        # Phase 1: Fill intervals in order of increasing chain_len (2, 3, ..., num_matrices)
        # so shorter subchains are already solved before any longer subchain reads them.
        for chain_len in range(2, num_matrices + 1):
            for left in range(0, num_matrices - chain_len + 1):
                right = left + chain_len - 1
                outer_rows = dimensions[left]
                outer_cols = dimensions[right + 1]
                best_cost: Optional[int] = None
    
                # Phase 2: Try every final split point `split` in [left, right - 1]:
                #   Left product  (A_left ... A_split)      has shape outer_rows x dimensions[split + 1]
                #   Right product (A_{split+1} ... A_right) has shape dimensions[split + 1] x outer_cols
                for split in range(left, right):
                    shared_dim = dimensions[split + 1]
                    merge_cost = outer_rows * shared_dim * outer_cols
                    candidate_cost = dp[left][split] + dp[split + 1][right] + merge_cost
    
                    if best_cost is None or candidate_cost < best_cost:
                        best_cost = candidate_cost
    
                dp[left][right] = best_cost
    
        # The top-right corner holds the minimum cost for the full chain 0 .. num_matrices - 1.
        return dp[0][num_matrices - 1]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture combining a row of adjacent building blocks where you are only allowed to glue neighboring pieces together: no matter what order you glue pairs, the finished block has the exact same outer width and height, yet gluing across a narrow bottleneck (3 wide) instead of a thick seam (20 wide) saves huge effort! Because any full parenthesization of matrices A_left ... A_right ends with one final multiplication joining (A_left ... A_split) and (A_{split+1} ... A_right), and each half's outer shape (dimensions[left] x dimensions[split + 1] and dimensions[split + 1] x dimensions[right + 1]) never depends on how that half was multiplied internally, the problem has optimal substructure — an optimal answer for a range is built directly from optimal answers for its smaller sub-ranges. We solve it with interval dynamic programming, filling a 2D table dp[left][right] for every contiguous subchain from shortest (chain_len = 2) to longest (chain_len = n) so every subchain is solved once and reused in O(1) time.

Why do simpler strategies fail? Trying all splits recursively without storing subproblem answers recomputes identical subchains 3^(n - 1) times (exploring Catalan-many parenthesizations, which grow roughly like 4^n). Meanwhile, a greedy algorithm — picking whichever single adjacent multiplication looks cheapest right now without looking ahead — gets trapped: on dimensions = [5, 9, 4, 4], multiplying 9 x 4 by 4 x 4 first costs 144 now plus 180 next = 324, whereas multiplying 5 x 9 by 9 x 4 first eliminates the 9 early for 180 + 80 = 260.

Here is how the table fills diagonal by diagonal on Example 1 (dimensions = [4, 20, 3, 10], giving A_0: 4x20, A_1: 20x3, A_2: 3x10):

Base (length 1):  dp[0][0] = 0,  dp[1][1] = 0,  dp[2][2] = 0
Length 2:         dp[0][1] =  4 * 20 *  3 = 240   (A_0 * A_1 -> shape 4x3)
                  dp[1][2] = 20 *  3 * 10 = 600   (A_1 * A_2 -> shape 20x10)
Length 3 (0..2):  split = 0 -> dp[0][0] + dp[1][2] + 4*20*10 =   0 + 600 + 800 = 1,400
                  split = 1 -> dp[0][1] + dp[2][2] + 4* 3*10 = 240 +   0 + 120 =   360 (winner!)

Return dp[0][2] -> 360

Complexity

Let n = len(dimensions) - 1 be the number of matrices in the chain (1 <= n <= 499).

  • Time: O(n^3). There are n * (n - 1) / 2 intervals of length at least 2, and an interval of length L checks L - 1 split points doing O(1) arithmetic each. Summing (n - L + 1) * (L - 1) from L = 2 to n gives (n^3 - n) / 6 inner-loop iterations—about 2.07 * 10^7 simple integer operations at the maximum n = 499.
  • Space: O(n^2). The 2D table dp allocates n * n integer slots (up to 499 * 499 ≈ 2.5 * 10^5 cells), using the upper triangle left <= right.

Edge cases

  • Single matrix (len(dimensions) == 2, n = 1): No multiplication occurs; range(2, 2) is empty, and dp[0][0] (0) is returned immediately.
  • Two matrices (len(dimensions) == 3, n = 2): Only one split (split = 0) exists, returning dimensions[0] * dimensions[1] * dimensions[2].
  • Dimensions equal to 1 ([1000, 1] or bottlenecks of 1): Allowed by 1 <= dimensions[i] <= 1000; 1-wide inner dimensions make merges across them ultra-cheap and require no special cases.
  • All dimensions identical ([d, d, ..., d]): Every parenthesization performs n - 1 multiplications of (d x d) by (d x d), so every order ties at (n - 1) * d^3.
  • Large integer totals (dimensions = [1000] * 500): Each merge can reach 1000^3 = 10^9 and the total can approach 5 * 10^11, which overflows signed 32-bit integers in C++/Java (~2.1 * 10^9); Python int has arbitrary precision so it never overflows.

Common mistakes

  • Off-by-one dimension indices in merge_cost: Matrix m is dimensions[m] x dimensions[m + 1], so splitting (left..split) from (split + 1..right) multiplies dimensions[left] * dimensions[split + 1] * dimensions[right + 1]. Writing dimensions[split] or dimensions[right] shifts shapes by one matrix.
  • Iterating left from 0 upward before chain_len: Computing dp[0][right] reads dp[split + 1][right] in rows below row 0; if those rows are still 0, dp uses uncomputed zeros instead of real costs. Always iterate by increasing chain_len (or iterate left downward from n - 1 to 0).
  • Setting num_matrices = len(dimensions) instead of len(dimensions) - 1: L dimension numbers define L - 1 matrices, so forgetting - 1 causes an IndexError at dimensions[right + 1].
  • Initializing best_cost = 0: Since every real multiplication cost is positive, starting best_cost at 0 causes candidate_cost < best_cost to never trigger, returning 0 for everything. Use None or math.inf.

Alternative approaches

  • Top-down recursion with memoization: Take the recursive brute_min_cost(left, right) function and add memoization — caching each (left, right) result in a dictionary or @functools.lru_cache so repeated calls return immediately in O(1) time. Same O(n^3) time and O(n^2) space, with recursion depth n (<= 499, within Python's default 1,000 frame limit, though bottom-up dp avoids recursion overhead completely).
  • Hu and Shing's polygon-triangulation algorithm (O(n log n)): Maps an n-matrix chain to triangulating a convex (n + 1)-vertex polygon with vertex weights dimensions[i] and finds the exact optimum in O(n log n) time, though it is far too intricate to code in a standard interview.
  • Standard library in NumPy: In real data-science pipelines, numpy.linalg.multi_dot([A0, A1, ...]) runs this exact O(n^3) dynamic program under the hood before executing the matrix multiplications.

Follow-up questions

  • How can you extend the table so it also outputs the exact parenthesized expression that achieves the minimum cost? Maintain a second n x n table best_split[left][right] and record best_split[left][right] = split whenever candidate_cost improves best_cost. Afterward, walk best_split recursively from (0, n - 1): return "M" + str(left) when left == right, and otherwise wrap the left and right subtrees in parentheses in O(n) reconstruction time (O(n^2) extra table space).

python def format_order(best_split: list[list[int]], left: int, right: int) -> str: if left == right: return f"M{left}" split = best_split[left][right] left_expr = format_order(best_split, left, split) right_expr = format_order(best_split, split + 1, right) return f"({left_expr} * {right_expr})"

  • How do runtime and memory scale with chain length, and why can't standard rolling-row tricks shrink the table to linear space? For n matrices, time is O(n^3) ((n^3 - n) / 6 split evaluations) and space is O(n^2). Unlike row-by-row grid DPs that only read the immediately preceding row, dp[left][right] simultaneously reads the entire horizontal prefix dp[left][left .. right - 1] and vertical suffix dp[left + 1 .. right][right] across all shorter lengths 1 .. chain_len - 1, so you cannot drop below O(n^2) space with this recurrence—you can only halve the constant factor by packing just the upper triangle left <= right into a flat n * (n + 1) // 2 array.

  • At chains of 10,000 matrices, why does cubic interval DP become impractical, and what faster exact or approximate methods exist? At n = 10,000, (n^3 - n) / 6 ≈ 1.67 * 10^11 inner operations and 10^8 table cells (~800 MB in Python) make cubic DP far too slow on a single CPU, and Knuth's optimization — an interval-DP trick that narrows the split loop to O(1) amortized work when optimal split points shift monotonically — does not apply because matrix-chain optimal splits can move backward (for example, on [6, 3, 5, 20, 20, 15, 5], the optimal split of 1-based M3..M6 is after M5, whereas for M4..M6 it moves left to M4). Instead, you would use Hu and Shing's exact O(n log n) algorithm, Chin's O(n) approximation algorithm (guaranteed within ~15.5% of optimal, and usually within 1–2% in practice), or parallelize across each fixed-chain_len diagonal on a GPU if an exact cubic pass in C++ is desired.

Follow-up questions

Similar questions

More Gsa interview questions

All 3 Gsa questions →