Transpose a Grid
Medium · rating 1250 · arrays, implementation
The first line contains the number of rows r and columns c. The next r lines each contain c integers. Print the transposed matrix: c lines of r integers, where the value at row i, column j becomes row j, column i.
Editorial
Transpose a Matrix flips a grid over its main diagonal so rows become columns — a fundamental matrix-manipulation task.
Approach
The value at row i, column j moves to row j, column i. For a non-square grid, allocate a fresh cols × rows matrix and copy each element to its transposed position.
T = [[0]*rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
T[j][i] = M[i][j]
return TComplexity
Time: O(rows × cols). Space: O(rows × cols); a square matrix transposes in place in O(1) extra space.