Allocate a columns-by-rows result and copy each input cell to the coordinates with reversed indices.
Complexity
O(rows * columns) time and O(rows * columns) output space.
Return the matrix formed by swapping every input row and column.
Allocate a columns-by-rows result and copy each input cell to the coordinates with reversed indices.
O(rows * columns) time and O(rows * columns) output space.
package main
func transpose(matrix [][]int) [][]int {
result := make([][]int, len(matrix[0]))
for column := range result {
result[column] = make([]int, len(matrix))
for row := range matrix {
result[column][row] = matrix[row][column]
}
}
return result
}
class Solution:
def transpose(self, matrix: list[list[int]]) -> list[list[int]]:
return [list(column) for column in zip(*matrix)]
function transpose(matrix: number[][]): number[][] {
return Array.from({ length: matrix[0].length }, (_, column) => matrix.map((row) => row[column]));
}