← back

Matrix times Matrix

#9 · Linear Algebra · Medium

⊣ Solve on deep-ml.com

Problem

Multiply two matrices together. If the number of columns in the first matrix does not equal the number of rows in the second, return -1.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def matrixmul(a: list[list[int|float]], b: list[list[int|float]]) -> list[list[int|float]]:
    if len(a[0]) != len(b):
        return -1
    rows_a = len(a)
    cols_b = len(b[0])
    shared = len(b)
    result = []
    for i in range(rows_a):
        row = []
        for j in range(cols_b):
            val = sum(a[i][k] * b[k][j] for k in range(shared))
            row.append(val)
        result.append(row)
    return result

Explanation

  1. Validate that the inner dimensions match (columns of A equals rows of B).
  2. For each position (i, j) in the result, compute the dot product of row i of A and column j of B.
  3. The result matrix has dimensions rows_a x cols_b.

Complexity

  • Time: O(n m k) where A is n x k and B is k x m
  • Space: O(n * m) for the result