Multiply Two Matrices
Arrays & HashingAuto-graded · 18 test casesLast 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_aandmatrix_bare floats in the range [-1000, 1000] - The inner dimension k matches between the two matrices (number of columns in
matrix_aequals number of rows inmatrix_b) - Return an empty list if
matrix_ais 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Matrix multiplication requires computing the dot product of each row from the first matrix with each column from the second matrix. The straightforward approach uses three nested loops: iterate over rows of the first matrix, columns of the second matrix, and the shared dimension for accumulation.
A practical optimization is to transpose the second matrix before computation. This transforms column access (which requires jumping between rows) into row access (which is contiguous in memory). While Python lists don't benefit as much from cache locality as lower-level languages, the pattern demonstrates the core optimization principle.
The algorithm:
- Handle edge cases: if the first matrix is empty, return an empty list
- Determine dimensions: m rows and k columns from the first matrix, n columns from the second
- Transpose the second matrix so
matrix_b_transposed[j]contains what was column j - For each position (i, j) in the output:
- Pair up corresponding elements from row i of the first matrix and the transposed row j
- Accumulate their products left to right into a running sum starting from 0.0
- Store the sum as the output element
Why It Works
The transpose preserves the mathematical relationship: matrix_b_transposed[j][x] equals matrix_b[x][j]. Therefore, summing matrix_a[i][x] * matrix_b_transposed[j][x] across all x gives the correct dot product for position (i, j).
Using zip to pair elements handles dimension matching automatically and iterates exactly k times per output element.
Complexity
Time: O(m · n · k) — we compute m·n output elements, each requiring k multiply-add operations.
Space: O(k · n) for the transposed matrix, plus O(m · n) for the output. Total auxiliary space is O(k·n + m·n).
Solution
from typing import List
def multiply_matrices(matrix_a: List[List[float]], matrix_b: List[List[float]]) -> List[List[float]]:
m = len(matrix_a)
if m == 0:
return []
k = len(matrix_a[0])
n = len(matrix_b[0]) if matrix_b else 0
# Transpose matrix_b so columns become rows for contiguous access
matrix_b_transposed = [[matrix_b[r][c] for r in range(len(matrix_b))] for c in range(n)]
result = []
for i in range(m):
row = []
for j in range(n):
total = 0.0
for x, y in zip(matrix_a[i], matrix_b_transposed[j]):
total += x * y
row.append(total)
result.append(row)
return result