DSA interview question
You're optimizing a deep learning inference pipeline at an AI infra company. A forward pass requires multiplying a chain of weight matrices together: M1 × M2 × M3 × ... × Mn. Matrix multiplication is associative — the final result is the same regardless of how you parenthesize the multiplications — but the computational cost (number of scalar multiplications) varies wildly depending on the order you multiply them in. Your job: given the dimensions of each matrix in the chain, find the minimum number of scalar multiplications needed to compute the full product, using a bottom-up (iterative, not recursive) DP approach — this matters because the inference engine runs this optimization at startup on every model load, and recursion with memoization adds overhead and stack-depth risk for long chains.
Matrices are given via an array arr of dimensions, where matrix i (1-indexed from 1 to n-1) has dimensions arr[i-1] x arr[i]. So for n matrices, arr has n+1 elements.
int matrixChainOrder(vector<int>& arr);
Input arr | Output | Explanation |
|---|---|---|
[40,20,30,10,30] | 26000 | 4 matrices: 40×20, 20×30, 30×10, 10×30 — optimal parenthesization gives 26000 multiplications |
[10,20,30] | 6000 | 2 matrices: 10×20, 20×30 — only one way to multiply → 102030 = 6000 |
[10,20,30,40,30] | 30000 | 4 matrices — optimal order yields 30000 |
[5,10] | 0 | Single matrix, no multiplication needed |
[1,2,3,4,5,6] | 58 | 5 matrices, classic small textbook example |
(Constraints typically: 1 <= arr.length <= 100, 1 <= arr[i] <= 500. Note: arr.length == n+1 for n matrices.)
arr guaranteed to represent a valid chain (i.e., arr.length == n+1 for n matrices, with consecutive dimensions compatible for multiplication)? (Yes by construction, since arr[i-1] x arr[i] defines matrix i.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in