Transpose of a Matrix

Implement transposeMatrix

Given a square matrix matrix, return its transpose — the matrix formed by reflecting every element across the main diagonal, so that result[j][i] = matrix[i][j] for every cell. Rows become columns and columns become rows. Copying into a brand new matrix always works, but a square matrix has a trick a rectangular one doesn't: since the transposed matrix has exactly the same dimensions as the original, every cell above the main diagonal can simply trade places with its mirror below it, transposing the whole matrix in place with no extra memory at all.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: matrix = [[1,2],[3,4]]

Output: [[1,3],[2,4]]

Example 3:

Input: matrix = [[5]]

Output: [[5]]

+ 6 hidden test cases run on Submit.

Constraints:

  • 1 ≤ n ≤ 50
  • -1000 ≤ matrix[i][j] ≤ 1000
  • matrix is square (n × n)

matrix =

[[1,2,3], [4,5,6], [7,8,9]]