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 matrix you get by turning every row into a column. The value at row i, column j moves to row j, column i. 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 first row [1, 2, 3] becomes the first column and [4, 5, 6] the second. Reading the result row by row gives [1, 4], [2, 5], [3, 6]: the 2 × 3 matrix turned into a 3 × 2 one.

lock icon+15 hidden tests on Submit

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 cases

Case 1

Case 2

Input

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

Expected

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