Matrix Chain Multiplication in DSA Typescript - Time & Space Complexity
Matrix Chain Multiplication finds the best way to multiply a chain of matrices with minimum cost.
We want to know how the time needed grows as the number of matrices increases.
Analyze the time complexity of this dynamic programming solution.
function matrixChainOrder(p: number[]): number {
const n = p.length - 1;
const dp: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let length = 2; length <= n; length++) {
for (let i = 0; i <= n - length; i++) {
let j = i + length - 1;
dp[i][j] = Infinity;
for (let k = i; k < j; k++) {
const cost = dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
if (cost < dp[i][j]) dp[i][j] = cost;
}
}
}
return dp[0][n - 1];
}
This code finds the minimum multiplication cost for a chain of matrices using dynamic programming.
Look at the loops that repeat work:
- Primary operation: The innermost loop tries all split points between matrices.
- How many times: For each pair of matrices, it tries all possible splits, repeating many times.
As the number of matrices grows, the operations increase quickly because of three nested loops.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,000 |
| 100 | About 1,000,000 |
| 1000 | About 1,000,000,000 |
Pattern observation: Operations grow roughly by the cube of the input size.
Time Complexity: O(n³)
This means if you double the number of matrices, the time needed grows about eight times.
[X] Wrong: "The solution runs in linear time because it just loops over the matrices."
[OK] Correct: There are three nested loops, so the work grows much faster than just going through the matrices once.
Understanding this time complexity helps you explain how dynamic programming improves over brute force and shows your grasp of nested loops and optimization.
"What if we used memoization with recursion instead of bottom-up DP? How would the time complexity change?"
Practice
Matrix Chain Multiplication problem?Solution
Step 1: Understand the problem objective
The Matrix Chain Multiplication problem aims to find the best way to multiply matrices to minimize cost.Step 2: Identify what is minimized
The cost minimized is the number of scalar multiplications, not the number of matrices or direct multiplication.Final Answer:
To find the minimum number of scalar multiplications needed to multiply a chain of matrices -> Option DQuick Check:
Goal = minimum scalar multiplications [OK]
- Confusing multiplication count with matrix count
- Thinking the problem multiplies matrices directly
- Assuming maximum matrices multiplication is the goal
Solution
Step 1: Identify input type for matrix dimensions
Matrix dimensions are given as an array of numbers representing sizes, sonumber[]is correct.Step 2: Identify return type for minimum cost
The function returns the minimum number of scalar multiplications, which is a number.Final Answer:
function matrixChainOrder(dimensions: number[]): number -> Option CQuick Check:
Input = number[], Output = number [OK]
- Using string instead of number array for dimensions
- Returning an array instead of a number
- Using 2D array or void return incorrectly
function matrixChainOrder(p: number[]): number {
const n = p.length - 1;
const m: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let L = 2; L <= n; L++) {
for (let i = 0; i < n - L + 1; i++) {
const j = i + L - 1;
m[i][j] = Number.MAX_SAFE_INTEGER;
for (let k = i; k < j; k++) {
const q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
if (q < m[i][j]) m[i][j] = q;
}
}
}
return m[0][n - 1];
}
console.log(matrixChainOrder([10, 20, 30, 40]));Solution
Step 1: Understand the input and matrix dimensions
The input array [10, 20, 30, 40] represents matrices of dimensions 10x20, 20x30, and 30x40.Step 2: Calculate minimum multiplication cost
Possible parenthesizations:
- (A1 x (A2 x A3)) = 20*30*40 + 10*20*40 = 24000 + 8000 = 32000
- ((A1 x A2) x A3) = 10*20*30 + 10*30*40 = 6000 + 12000 = 18000 (minimum)Final Answer:
18000 -> Option AQuick Check:
Minimum multiplications = 18000 [OK]
- Calculating cost for only one parenthesization
- Mixing matrix dimensions order
- Forgetting to add multiplication costs correctly
function matrixChainOrder(p: number[]): number {
const n = p.length - 1;
const m: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let L = 2; L <= n; L++) {
for (let i = 0; i < n - L + 1; i++) {
const j = i + L - 1;
m[i][j] = Infinity;
for (let k = i; k < j; k++) {
const q = m[i][k] + m[k + 1][j] + p[i] * p[k] * p[j];
if (q < m[i][j]) m[i][j] = q;
}
}
}
return m[0][n - 1];
}Solution
Step 1: Identify the multiplication cost formula error
The cost formula uses incorrect indices:p[i] * p[k] * p[j]should usep[k + 1]andp[j + 1]to represent matrix dimensions correctly.Step 2: Confirm other parts are correct
Initialization with 0 is correct for diagonal, loop ranges are correct, and return index is correct.Final Answer:
Changep[i] * p[k] * p[j]top[i] * p[k + 1] * p[j + 1]-> Option AQuick Check:
Correct cost formula indices fix error [OK]
- Using wrong indices for matrix dimensions in cost calculation
- Changing loop bounds unnecessarily
- Returning wrong matrix cell
Solution
Step 1: Understand matrix dimensions and chain length
The array represents matrices: 5x10, 10x3, 3x12, 12x5, 5x50, 50x6 (6 matrices).Step 2: Use dynamic programming to find minimum cost
By calculating all splits and costs:
- Minimum cost found is 2010 scalar multiplications.Final Answer:
2010 -> Option BQuick Check:
Minimum scalar multiplications = 2010 [OK]
- Calculating only one split option
- Mixing up matrix dimensions order
- Forgetting to add multiplication costs for subproblems
Ready to prove it?
Pass the test and this pattern moves unknown
