← back

Transpose of a Matrix

#2 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Write a function to compute the transpose of a given matrix. The transpose flips a matrix over its diagonal, switching rows and columns.

Solution

1
2
3
4
def transpose_matrix(a: list[list[int|float]]) -> list[list[int|float]]:
    rows = len(a)
    cols = len(a[0])
    return [[a[r][c] for r in range(rows)] for c in range(cols)]

Explanation

  1. Determine the number of rows and columns in the original matrix.
  2. For each column index c in the original, build a new row by collecting element a[r][c] for every row index r.
  3. The result has dimensions cols x rows.

Complexity

  • Time: O(m * n)
  • Space: O(m * n) for the transposed matrix