DrawCode Algorithm Visualizer • Dynamic Programming • Hard

Matrix Chain Multiplication

Tags: DP, 2D, Interval, Optimization

1. One-Liner

MCM minimizes total scalar multiplications to compute A1×…×An by splitting chains: dp[i][j] = optimal cost for matrices i..j.


2. The Problem It Solves

Matrix multiplication is associative but not commutative; different parenthesizations change operation count dramatically. You need the minimum cost schedule given dimensions p[0..n].


3. The Core Idea

Try every split k between i and j: cost = dp[i][k]+dp[k+1][j]+p[i-1]·p[k]·p[j]—optimal substructure on intervals.


4. How It Works (Step-by-Step)

StepWhat Happens
1dp[i][i]=0
2Increase length L from 2 to n
3For each [i,j], try all k
4Take minimum

5. Dry Run Example

Dims [1,2,3,4] (three matrices)—compute costs for splits; optimal cost 18 for ((A1A2)A3) style evaluation (verify with standard example).


6. Key Properties

PropertyValue
Interval DPClassic
TimeO()

7. Where It Is Used

DomainUse
CompilersExpression reordering intuition
MLTensor contraction planning (advanced)

8. Interview Tips

Print parenthesization via split table; contrast greedy failure cases.


9. Comparison with Other Algorithms

ProblemStructure
MCMInterval split
Optimal BSTSimilar interval flavor

10. Complexity

MetricValue
TimeO()
SpaceO()

Implementation Example (PYTHON)

def matrix_chain_order(p: list[int]) -> int:
    n = len(p) - 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] = min(
                dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1] for k in range(i, j))
    return dp[0][n - 1]

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer