Transpose Matrix
Easy matrix
Description
Constraints
1 <= rows, cols <= 100
Examples
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Hints (1)
- The element at (r, c) moves to (c, r).
Solutions
Swap indices. · Time O(rows*cols) · Space O(rows*cols)
func transpose(matrix [][]int) [][]int {
rows, cols := len(matrix), len(matrix[0])
out := make([][]int, cols)
for c := 0; c < cols; c++ {
out[c] = make([]int, rows)
for r := 0; r < rows; r++ {
out[c][r] = matrix[r][c]
}
}
return out
}
Swap indices. · Time O(rows*cols) · Space O(rows*cols)
function transpose(matrix) {
return matrix[0].map((_, c) => matrix.map(row => row[c]));
}
Swap indices. · Time O(rows*cols) · Space O(rows*cols)
function transpose($matrix) {
$out = [];
for ($c = 0; $c < count($matrix[0]); $c++) {
$row = [];
for ($r = 0; $r < count($matrix); $r++) { $row[] = $matrix[$r][$c]; }
$out[] = $row;
}
return $out;
}
Swap indices. · Time O(rows*cols) · Space O(rows*cols)
def transpose(matrix):
return [list(row) for row in zip(*matrix)]
Swap indices. · Time O(rows*cols) · Space O(rows*cols)
function transpose(matrix: number[][]): number[][] {
return matrix[0].map((_, c) => matrix.map(row => row[c]));
}
Create a free account to submit solutions, track progress and save problems.
Create account