Transpose Matrix

Given a 2D integer array `matrix`, return the transpose of `matrix`. The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices: the value at `matrix[r][c]` moves to `result[c][r]`. An `m x n` matrix becomes an `n x m` matrix.

30:00

Transpose Matrix
easy
Free written solution
Topics
Companies

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices: the value at matrix[r][c] moves to result[c][r]. An m x n matrix becomes an n x m matrix.

Example 1:
Input: {"matrix":[[1,2,3],[4,5,6],[7,8,9]]}
Output: [[1,4,7],[2,5,8],[3,6,9]]
Constraints:
  • m==matrix.lengthm == \text{matrix.length}

  • n==matrix[i].lengthn == \text{matrix}[i].\text{length}

  • 1≤m,n≤10001 \leq m, n \leq 1000

  • 1≤m⋅n≤1051 \leq m \cdot n \leq 10^5

  • −109≤matrix[i][j]≤109-10^9 \leq \text{matrix}[i][j] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

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

The input is 3 x 3, so the transpose is 3 x 3. Allocate an empty 3 x 3 result; every value at [r][c] will land at [c][r].

[r][c] → [c][r]

matrix (3 x 3)

c0

c1

c2

r0

1
2
3

r1

4
5
6

r2

7
8
9

→

result (3 x 3)

r0

r1

r2

c0

c1

c2

Each colour is one input row. It lands as the same-numbered column of the result. The dashed line is the main diagonal, where r = c and values stay put.

Variables
VariableValue
m3
n3
DepthFunction Call
Stack empty
0/13