Transpose Matrix
Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices of every element. For every cell, the value at matrixi[j] moves to resultj[i] .
Constraints
- m == matrix.length
- n == matrixi.length
- 1 ≤ m, n ≤ 1000
- -109 ≤ matrixi[j] ≤ 109
Example
matrix = [[1, 2, 3], [4, 5, 6]][[1, 4], [2, 5], [3, 6]]Explanation Row 0 [1, 2, 3] becomes column 0 of the result, and row 1 [4, 5, 6] becomes column 1.
In plain terms
- Transpose
- Flipping a grid of values so that rows become columns and columns become rows.
Swap row and column indices for every cell
matrix[0][0]=1 moves to result[0][0]=1.
What happens in this step
matrix[0][0] = 1 result[0][0] = matrix[0][0] = 1
Steps to visualize
- Create a new result grid with rows and columns swapped in size.
- Walk through every cell (i, j) of the original matrix.
- Place matrixi[j] into resultj[i].
- Once every cell has been copied, the result is the transposed matrix.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
matrix[0][0]=1 moves to result[0][0]=1.
What happens in this step
matrix[0][0] = 1 result[0][0] = matrix[0][0] = 1
Solution
function transpose(matrix) {
const m = matrix.length;
const n = matrix[0].length;
const result = Array.from({ length: n }, () => new Array(m).fill(0));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}- Time
- O(m * n)
- Space
- O(m * n)
Test cases
| Input | Expected | Covers |
|---|---|---|
matrix = [[1, 2, 3], [4, 5, 6]] | [[1, 4], [2, 5], [3, 6]] | example from the docstring |
matrix = [[1, 2], [3, 4]] | [[1, 3], [2, 4]] | a square matrix transposed in place conceptually |
matrix = [[5]] | [[5]] | smallest valid input, a 1x1 matrix |
matrix = [[1, 2, 3]] | [[1], [2], [3]] | a single row becomes a single column |
matrix = [[1], [2], [3]] | [[1, 2, 3]] | a single column becomes a single row |
matrix = [[-1, -2], [-3, -4]] | [[-1, -3], [-2, -4]] | negative values transposed correctly |