Menu
CoddyTech

Transpose Matrix

You get a matrix of integers as a list of rows: matrix[i][j] is the value in row i, column j. Return its transpose: the value at row i, column j moves to row j, column i, so every row becomes a column. The matrix does not have to be square: an m × n matrix becomes an n × m one.

Function

transpose(matrix: integer-2d-array) → integer-2d-array
matrixinteger-2d-array
the m × n matrix, as a list of m rows of n integers
Returnsinteger-2d-array
the n × m transpose, as a list of n rows of m integers

Constraints

  • 1 ≤ m, n ≤ 1000, where m = matrix.length and n = matrix[i].length
  • m × n ≤ 5000
  • Every row has the same length n.
  • -1000 ≤ matrix[i][j] ≤ 1000

Examples

Input
matrix = [[1, 2, 3], [4, 5, 6]]
Output
[[1, 4], [2, 5], [3, 6]]
Explanation
The row [1, 2, 3] becomes the first column and [4, 5, 6] the second. Read row by row, the result is [1, 4], [2, 5], [3, 6]: a 3 × 2 matrix.
challenge icon

Follow-up

Suppose the matrix is stored as one flat array of m × n values, row after row. Can you transpose a non-square matrix inside that array, with no second array?

Reset code
def transpose(matrix):
    # Write code here

Test #1

Test #2

Argument

matrix = [[1, 2, 3], [4, 5, 6]]

Expected Output

[[1, 4], [2, 5], [3, 6]]