Transpose a matrix
Easy TimeO(n·m) SpaceO(n·m)
Transposing a matrix swaps its rows and columns, so the value at row i, column j moves to row j, column i and [[1, 2, 3], [4, 5, 6]] becomes [[1, 4], [2, 5], [3, 6]]. Given matrix, whose rows all have the same length, return the transpose as a new matrix. The shape changes — an m × n matrix becomes n × m — which is why a rectangular one cannot be written back over itself.
Examples
Example 1
- Input
- matrix = [[1, 2, 3], [4, 5, 6]]
- Output
- Two rows of three become three rows of two: the shape itself is transposed.
[[1,4],[2,5],[3,6]]
Example 2
- Input
- matrix = [[1, 2], [3, 4]]
- Output
- Square, so the shape is unchanged and only the
[[1,3],[2,4]]2and the3trade places.
The Code
function transpose(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const out = [];
for (let c = 0; c < cols; c++) {
const newRow = [];
for (let r = 0; r < rows; r++) {
newRow.push(matrix[r][c]);
}
out.push(newRow);
}
return out;
}
transpose([[1, 2, 3], [4, 5, 6]]);Done
More like this
All matrices & grids examples (7) →- Spiral order Four shrinking boundaries peel the grid one ring at a time.
- Rotate a matrix Transpose, then mirror each row — a rotation in two easy passes.
- Flood fill The paint-bucket tool — recurse outwards while the colour matches.
- Count islands Every unvisited land cell starts an island — then sink the rest.
- Set matrix zeroes Record which rows and columns to blank before blanking anything.
- Maximal rectangle Every row is a histogram — solve that, then sweep downwards.