42. Transpose Matrix

EasyArrayArray

Given a 2D integer array matrix, return the transpose of the matrix. The transpose of a matrix is formed by swapping its rows and columns, i.e., transpose[i][j] = matrix[j][i].

Input: A 2D integer array matrix of size m x n.

Output: The transposed matrix of size n x m.

Examples

Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Explanation: transpose[i][j]=matrix[j][i]. Row0 becomes Col0: [1,4,7].
Example 2
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Explanation: 2x3 matrix transposes to 3x2.
Example 3
Input: [[1]]
Output: [[1]]
Explanation: 1x1 matrix is its own transpose.

Constraints

Asked by

GoogleMicrosoftBloombergAmazonMeta
Solve this problem in the editor →