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), andM_2(3 x 10).- Evaluating
(M_0 * M_1) * M_2first forms a4 x 3intermediate matrix for4 * 20 * 3 = 240operations, then multiplies(4 x 3)by(3 x 10)for4 * 3 * 10 = 120operations, totaling240 + 120 = 360. - Evaluating
M_0 * (M_1 * M_2)costs(20 * 3 * 10) + (4 * 20 * 10) = 600 + 800 = 1400. The smaller total is360.
- Evaluating
Example 2
- Input:
dimensions = [12, 3, 8, 2] - Output:
120 - Explanation: Here
M_0is12 x 3,M_1is3 x 8, andM_2is8 x 2.- Evaluating
(M_0 * M_1) * M_2costs(12 * 3 * 8) + (12 * 8 * 2) = 288 + 192 = 480. - Evaluating
M_0 * (M_1 * M_2)first collapses the8-wide inner dimension into a3 x 2product for3 * 8 * 2 = 48operations, followed by12 * 3 * 2 = 72operations, totaling48 + 72 = 120.
- Evaluating
Constraints
2 <= len(dimensions) <= 5001 <= dimensions[i] <= 1000
Step-by-step walkthrough
Understand how matrix shapes and parenthesization change the cost
A list
dimensionsof lengthLdescribesnum_matrices = L - 1matrices in a fixed left-to-right lineup. Using0-based indexing, matrixA_mhasdimensions[m]rows anddimensions[m + 1]columns, so adjacent matrices always share their inner dimension.Matrix multiplication is associative —
(A_0 * A_1) * A_2andA_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,400Notice 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 to144 + (5 * 9 * 4) = 324, whereas multiplying(5 x 9) * (9 x 4) = 180first eliminates the large9early for180 + (5 * 4 * 4) = 260. And iflen(dimensions) == 2, there is only1matrix and zero multiplications, so the cost is0.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 hasdimensions[left]rows anddimensions[split + 1]columns. - No matter what order we used inside the right half
A_{split+1} ... A_right, its resulting matrix always hasdimensions[split + 1]rows anddimensions[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_rightviasplitmust use the best way to computeleft..splitplus the best way to compute(split + 1)..right.- No matter what order we used inside the left half
Why plain recursion explodes—and how a 2D table fixes it
If we write a plain recursive function
min_cost(left, right)that tries everysplitfromlefttoright - 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_costWhy is this far too slow for up to
499matrices? Because the exact same subchains get solved over and over ((1, 2)is recomputed inside(0, 2),(1, 3),(0, 3), ...), making3^(n - 1)total calls!Yet there are only
n * (n + 1) / 2distinct pairs(left, right)with0 <= left <= right < n. By storing each subchain's minimum cost once in a 2D tabledp[left][right](interval dynamic programming), we never solve any subchain twice:- Base case (
chain_len = 1):dp[i][i] = 0for every single matrixA_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]).
- Base case (
Why we must fill the table by increasing chain length
Look at which cells
dp[left][right]reads inside thedpgrid: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
leftfrom0downward ton - 1,dp[0][2]would try to readdp[1][2]before row 1 had been computed! Looping onchain_len = 2, 3, ..., num_matricesfills 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_costNotice we initialize
best_cost = Nonerather than0(otherwise0would falsely beat every positive multiplication cost!).Trace Example 1 diagonal by diagonal
Let's trace
dimensions = [4, 20, 3, 10], which hasnum_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 ]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 aren * (n - 1) / 2intervals of length at least2, and an interval of lengthLchecksL - 1split points doingO(1)arithmetic each. Summing(n - L + 1) * (L - 1)fromL = 2tongives(n^3 - n) / 6inner-loop iterations—about2.07 * 10^7simple integer operations at the maximumn = 499. - Space:
O(n^2). The 2D tabledpallocatesn * ninteger slots (up to499 * 499 ≈ 2.5 * 10^5cells), using the upper triangleleft <= right.
Edge cases
- Single matrix (
len(dimensions) == 2,n = 1): No multiplication occurs;range(2, 2)is empty, anddp[0][0](0) is returned immediately. - Two matrices (
len(dimensions) == 3,n = 2): Only one split (split = 0) exists, returningdimensions[0] * dimensions[1] * dimensions[2]. - Dimensions equal to
1([1000, 1]or bottlenecks of1): Allowed by1 <= 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 performsn - 1multiplications 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 reach1000^3 = 10^9and the total can approach5 * 10^11, which overflows signed 32-bit integers in C++/Java (~2.1 * 10^9); Pythoninthas arbitrary precision so it never overflows.
Common mistakes
- Off-by-one dimension indices in
merge_cost: Matrixmisdimensions[m] x dimensions[m + 1], so splitting(left..split)from(split + 1..right)multipliesdimensions[left] * dimensions[split + 1] * dimensions[right + 1]. Writingdimensions[split]ordimensions[right]shifts shapes by one matrix. - Iterating
leftfrom0upward beforechain_len: Computingdp[0][right]readsdp[split + 1][right]in rows below row0; if those rows are still0,dpuses uncomputed zeros instead of real costs. Always iterate by increasingchain_len(or iterateleftdownward fromn - 1to0). - Setting
num_matrices = len(dimensions)instead oflen(dimensions) - 1:Ldimension numbers defineL - 1matrices, so forgetting- 1causes anIndexErroratdimensions[right + 1]. - Initializing
best_cost = 0: Since every real multiplication cost is positive, startingbest_costat0causescandidate_cost < best_costto never trigger, returning0for everything. UseNoneormath.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_cacheso repeated calls return immediately inO(1)time. SameO(n^3)time andO(n^2)space, with recursion depthn(<= 499, within Python's default1,000frame limit, though bottom-updpavoids recursion overhead completely). - Hu and Shing's polygon-triangulation algorithm (
O(n log n)): Maps ann-matrix chain to triangulating a convex(n + 1)-vertex polygon with vertex weightsdimensions[i]and finds the exact optimum inO(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 exactO(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 ntablebest_split[left][right]and recordbest_split[left][right] = splitwhenevercandidate_costimprovesbest_cost. Afterward, walkbest_splitrecursively from(0, n - 1): return"M" + str(left)whenleft == right, and otherwise wrap the left and right subtrees in parentheses inO(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
nmatrices, time isO(n^3)((n^3 - n) / 6split evaluations) and space isO(n^2). Unlike row-by-row grid DPs that only read the immediately preceding row,dp[left][right]simultaneously reads the entire horizontal prefixdp[left][left .. right - 1]and vertical suffixdp[left + 1 .. right][right]across all shorter lengths1 .. chain_len - 1, so you cannot drop belowO(n^2)space with this recurrence—you can only halve the constant factor by packing just the upper triangleleft <= rightinto a flatn * (n + 1) // 2array. -
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^11inner operations and10^8table 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 thesplitloop toO(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-basedM3..M6is afterM5, whereas forM4..M6it moves left toM4). Instead, you would use Hu and Shing's exactO(n log n)algorithm, Chin'sO(n)approximation algorithm (guaranteed within ~15.5% of optimal, and usually within 1–2% in practice), or parallelize across each fixed-chain_lendiagonal on a GPU if an exact cubic pass in C++ is desired.
Follow-up questions
- How can you extend the table so it also outputs the exact parenthesized expression that achieves the minimum cost?
- How do runtime and memory scale with chain length, and why can't standard rolling-row tricks shrink the table to linear space?
- At chains of 10,000 matrices, why does cubic interval DP become impractical, and what faster exact or approximate methods exist?
Similar questions
- Reviewing a Deep-Vision Bridge Failure Proposal
- Market-Neutral Equity Return Prediction with News Sentiment
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance