867 Transpose Matrix
Published:
Problem
Solution
Intuition
This problem is very simple as transposing a matrix can be done very neatly. We just need to initialize an array to store the transposed matrix and then begin filling it in.
Approach
- Initialize a matrix with a number of rows equal to the number of columns in the original matrix and a number of columns equal to the number of rows in the original matrix.
- Traverse through the original matrix and place each element in their transposed position.
Complexity
- Time complexity: $O(n*m)$. We iterate through each element in the array once. The array is not guaranteed to be square.
- Space complexity: $O(n*m)$. We create another array for storing the result of the same size as the original array.
Code
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
res = [[0]*len(matrix) for _ in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
res[j][i] = matrix[i][j]
return res