Workspace Matrix Chain Multiplication
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Matrix Chain Multiplication visualizer

Learn Matrix Chain Multiplication with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice partition and interval dp.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 11Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    40,
    20,
    30,
    10,
    30
  ],
  "mode": "matrix"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,mode
},s)=>{
let n=mode==="matrix"?a.length-1:a.length-2,d=Array.from({
length:n+2
},()=>Array(n+2).fill(0));
for(let len=1;
len<=n;
len++)for(let i=1;
i+len-1<=n;
i++){
let j=i+len-1;
if(mode==="matrix"&&len===1)continue;
let b=mode==="burst"?0:Infinity;
for(let k=i;
k<=(mode==="matrix"?j-1:j);
k++){
let v=mode==="matrix"?d[i][k]+d[k+1][j]+a[i-1]*a[k]*a[j]:d[i][k-1]+d[k+1][j]+(mode==="cut"?a[j+1]-a[i-1]:a[i-1]*a[k]*a[j+1]);
b=mode==="burst"?Math.max(b,v):Math.min(b,v);
s("Evaluate interval split",{
Input:a,DP:d,Interval:[i,k,j],Candidate:[v],Best:[b]
})
}
d[i][j]=b
}
return d[1][n]
};

Execution canvas

Active Changed
STEP 1

Evaluate interval split

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Input5 items
DP6 rows
Interval3 items
Candidate1 items
Best1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Dynamic Programming · Partition and interval DP

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

{
  "a": [
    40,
    20,
    30,
    10,
    30
  ],
  "mode": "matrix"
}

Execution steps

  1. Evaluate interval split

Computed output

26000
JavaScript reference implementation
const solve = ({
  a,mode
},s)=>{
  let n=mode==="matrix"?a.length-1:a.length-2,d=Array.from({
    length:n+2
  },()=>Array(n+2).fill(0));
  for(let len=1;
  len<=n;
  len++)for(let i=1;
  i+len-1<=n;
  i++){
    let j=i+len-1;
    if(mode==="matrix"&&len===1)continue;
    let b=mode==="burst"?0:Infinity;
    for(let k=i;
    k<=(mode==="matrix"?j-1:j);
    k++){
      let v=mode==="matrix"?d[i][k]+d[k+1][j]+a[i-1]*a[k]*a[j]:d[i][k-1]+d[k+1][j]+(mode==="cut"?a[j+1]-a[i-1]:a[i-1]*a[k]*a[j+1]);
      b=mode==="burst"?Math.max(b,v):Math.min(b,v);
      s("Evaluate interval split",{
        Input:a,DP:d,Interval:[i,k,j],Candidate:[v],Best:[b]
      })
    }
    d[i][j]=b
  }
  return d[1][n]
};

Continue learning

Practice related DSA questions in the same topic.