Cheapest Parenthesization for a Chain of Matrix Products
Last updated: November 29, 2026
Quick Overview
Given the dimensions of matrices A1 through An to be multiplied in order, return the minimum number of scalar multiplications needed and an optimal parenthesization string.
MathWorks
November 29, 20260
0
0 solved
Given the dimensions of matrices A1 through An to be multiplied in order, return the minimum number of scalar multiplications needed and an optimal parenthesization string.
Matrix computation is core to MATLAB, and an expression like A*B*C can differ by orders of magnitude in cost depending on evaluation order. MathWorks interviewers use this to test interval dynamic programming, reconstruction of the optimal choice, and the ability to connect an algorithm to how a compiler or JIT might rewrite expressions.
What the Interviewer Expects
- Defines the subproblem cost[i][j] for the product Ai..Aj
- Writes the recurrence over split point k with the dims[i]*dims[k+1]*dims[j+1] term
- Fills the table by increasing chain length so dependencies are ready
- Stores split points and rebuilds the parenthesization
- States O(n^3) time and O(n^2) space and mentions when that is acceptable
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- When is it worth spending O(n^3) at runtime versus deciding the order at code generation time?
- How does the answer change if the final matrix is multiplied by a vector, as in A*B*C*x?
- Is there a greedy rule that works? Give a counterexample for 'multiply the smallest pair first'.
- How would you account for sparse matrices whose cost depends on nonzeros rather than dimensions?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: dims of length n+1, where matrix i (0-based) is dims[i] x dims[i+1]. Output: (min_cost, expr) where cost counts scalar multiplications under the standard model (multiplying p x q by q x r...
High-Level Design
Let cost[i][j] be the cheapest way to compute Ai..Aj. A single matrix costs 0. Otherwise the last multiplication splits the chain at some k: `cost[i][j] = min over k of cost[i][k] + cost[k+1][j] +...