Transpose Matrix

Easy~10 min

Given a 2D matrix matrix, return its transpose.

The transpose of a matrix flips it over its main diagonal — rows become columns and columns become rows. In other words, result[j][i] = matrix[i][j].

The input matrix may be rectangular (not necessarily square).

Examples

Example 1
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Explanation: The 2x3 matrix becomes a 3x2 matrix. Row 0 [1,2,3] becomes column 0.
Example 2
Input: matrix = [[1,2],[3,4],[5,6]]
Output: [[1,3,5],[2,4,6]]
Explanation: The 3x2 matrix becomes a 2x3 matrix.
Example 3
Input: matrix = [[1]]
Output: [[1]]
Explanation: A 1x1 matrix is its own transpose.

Constraints

  • 1 <= matrix.length, matrix[i].length <= 100
  • -1000 <= matrix[i][j] <= 1000
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run