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
[[1,4],[2,5],[3,6]]
Two rows of three become three rows of two: the shape itself is transposed.

Example 2

Input
matrix = [[1, 2], [3, 4]]
Output
[[1,3],[2,4]]
Square, so the shape is unchanged and only the 2 and the 3 trade 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
Step through transpose([[1, 2, 3], [4, 5, 6]]) call by call