Transpose Matrix
Difficulty: Easy · Pattern: Matrix · LeetCode #867
Return the transpose of matrix, flipping it over its main diagonal so rows become columns. The matrix may be non-square.
Examples
text
[[1,2,3],[4,5,6],[7,8,9]] → [[1,4,7],[2,5,8],[3,6,9]]
[[1,2,3],[4,5,6]] → [[1,4],[2,5],[3,6]]Hints
- An R×C matrix transposes to C×R, so for non-square input you need a new array.
Approach
Allocate a C × R result and set res[c][r] = m[r][c]. For square matrices you can transpose in place by swapping m[r][c] with m[c][r] for c > r. That swap is the first half of Rotate Image. In Python, list(map(list, zip(*m))) is the idiom.
Complexity
Time: O(R·C). Space: O(R·C) for the output.
Python solution
def transpose(matrix):
return [list(col) for col in zip(*matrix)]JavaScript solution
function transpose(matrix) {
const R = matrix.length, C = matrix[0].length;
return Array.from({ length: C }, (_, c) => Array.from({ length: R }, (_, r) => matrix[r][c]));
}