KatInterview

Multiply Two Matrices

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingmatrixnested-loopsmath

Last updated

Tests understanding of matrix multiplication mechanics, nested iteration, and accumulation patterns.

Write a function that computes the product of two matrices.

Given two matrices matrix_a with dimensions m×k and matrix_b with dimensions k×n, return their product, a matrix with dimensions m×n.

The product is defined such that each element at position (i, j) in the result equals the sum of element-wise products of row i from matrix_a and column j from matrix_b.

Formally: result[i][j] = sum(matrix_a[i][x] * matrix_b[x][j] for x in range(k))

All matrix elements are floating-point numbers. Accumulate products in the order they appear (left to right by increasing index).

Constraints

  • 0 ≤ m ≤ 100
  • 0 ≤ k ≤ 100
  • 0 ≤ n ≤ 100
  • All elements of matrix_a and matrix_b are floats in the range [-1000, 1000]
  • The inner dimension k matches between the two matrices (number of columns in matrix_a equals number of rows in matrix_b)
  • Return an empty list if matrix_a is empty
  • If k = 0, return m rows where each row is an empty list

Examples

Example 1

Input: multiply_matrices([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]])

Output: [[58, 64], [139, 154]]

Example 2

Input: multiply_matrices([[1, 0], [0, 1]], [[3, 4], [5, 6]])

Output: [[3, 4], [5, 6]]

Example 3

Input: multiply_matrices([[1.5, -2], [0.5, 3]], [[-1, 2], [4, 0.5]])

Output: [[-9.5, 2], [11.5, 2.5]]

Hints

Hint 1

The result matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.

Hint 2

For each output position (i,j), you need to compute a dot product between row i of the first matrix and column j of the second matrix.

Hint 3

Transposing the second matrix before computation can make column access more efficient by converting it to row access.