Return the transpose of a matrix by swapping its rows and columns.
Transpose Matrix
Given a 2D matrix matrix, return its transpose.
The transpose of a matrix is formed by turning rows into columns. If matrix has m rows and n columns, the result should have n rows and m columns, where the element at position [i][j] in the input appears at position [j][i] in the output.
Input Format
- A 2D integer matrix
matrixwithmrows andncolumns.
Output Format
- Return a new 2D matrix representing the transpose of
matrix.
Constraints
1 <= m, n- The matrix may be rectangular.
- Elements should be preserved exactly; only their positions change.
Hints
- Think about how to build the output dimensions before filling values.
- The value at row
rand columncin the input should go to rowcand columnrin the answer.
Input Format
A 2D integer matrix matrix with m rows and n columns.
Output Format
Return a 2D integer matrix of size n x m that is the transpose of the input.
Constraints
1 <= m, n- The matrix can be rectangular.
- Preserve all values exactly.
- Return a new matrix rather than modifying in place unless explicitly allowed.
Example 1
Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[[1,4,7],[2,5,8],[3,6,9]]
Explanation
Rows become columns: the first column of the input becomes the first row of the output.
Example 2
Input
matrix = [[1,2,3],[4,5,6]]
Output
[[1,4],[2,5],[3,6]]
Explanation
For a non-square matrix, the output dimensions are swapped from 2x3 to 3x2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.