Matrices: Transpose a Matrix
You are given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Answer
The main idea consists of two steps:
Step 1: Create an empty result matrix of the correct transposed size. We use
res = [[0]*rows for i in range(cols)]. This means we create as many rows in the result as there are columns in the original, and each row has as many entries as the original had rows.Step 2: Fill the result matrix by swapping row and column indices using
res[c][r] = matrix[r][c]. A nested for loop is used to visit each \((r, c)\) position in the original matrix.
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows, cols = len(matrix), len(matrix[0])
res = [[0]*rows for i in range(cols)]
for r in range(rows):
for c in range(cols):
res[c][r] = matrix[r][c]
return resAlternative method (Pythonic one-liner):
transposed = [list(row) for row in zip(*matrix)]Programming lesson: In zip(*matrix), the symbol * is the unpacking operator. It takes the list of rows [row1, row2, row3, ...] and feeds them into zip as separate arguments:
This makes zip combine the first elements of each row together, then the second elements, and so on, exactly forming the transpose. This gives a list of tuples hence the need for the list comprehension.