Matrix Multiplication - Problem

Given two matrices A and B, multiply them together and return the resulting matrix.

Matrix multiplication is only possible when the number of columns in the first matrix equals the number of rows in the second matrix. If the matrices are incompatible for multiplication, return "Error: Incompatible dimensions".

For compatible matrices A (m×n) and B (n×p), the result will be a matrix C (m×p) where each element C[i][j] is the dot product of row i from matrix A and column j from matrix B.

Formula: C[i][j] = Σ(A[i][k] * B[k][j]) for k from 0 to n-1

Input & Output

Example 1 — Basic 2×3 and 3×2 Matrices
$ Input: matrixA = [[1,2,3],[4,5,6]], matrixB = [[7,8],[9,10],[11,12]]
Output: [[58,64],[139,154]]
💡 Note: Matrix A is 2×3 and Matrix B is 3×2, so result is 2×2. C[0][0] = 1×7 + 2×9 + 3×11 = 7+18+33 = 58. C[0][1] = 1×8 + 2×10 + 3×12 = 8+20+36 = 64.
Example 2 — Square Matrices
$ Input: matrixA = [[1,2],[3,4]], matrixB = [[5,6],[7,8]]
Output: [[19,22],[43,50]]
💡 Note: Both matrices are 2×2. C[0][0] = 1×5 + 2×7 = 5+14 = 19. C[1][1] = 3×6 + 4×8 = 18+32 = 50.
Example 3 — Incompatible Dimensions
$ Input: matrixA = [[1,2]], matrixB = [[3],[4],[5]]
Output: "Error: Incompatible dimensions"
💡 Note: Matrix A is 1×2 and Matrix B is 3×1. Since columns of A (2) ≠ rows of B (3), multiplication is impossible.

Constraints

  • 1 ≤ matrixA.length, matrixA[0].length ≤ 100
  • 1 ≤ matrixB.length, matrixB[0].length ≤ 100
  • -1000 ≤ matrixA[i][j], matrixB[i][j] ≤ 1000

Visualization

Tap to expand
INPUTMatrix A (2×3)[1, 2, 3][4, 5, 6]Matrix B (3×2)[7, 8][9, 10][11, 12]Compatible: cols(A) = rows(B) = 3ALGORITHM1Check dimensions2Initialize result matrix3Triple nested loops4Compute dot productsC[i][j] = Σ A[i][k] × B[k][j]Time: O(m×n×p)RESULTMatrix C (2×2)[58, 64][139, 154]Dimensions: 2×2✓ Multiplication CompleteKey Insight:Matrix multiplication combines rows and columns through dot products,requiring systematic computation of all element pairs with triple nested loops.TutorialsPoint - Matrix Multiplication | Triple Nested Loop Algorithm
Asked in
Google 35 Microsoft 28 Amazon 22 Facebook 18
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen