Transpose Matrix - Problem

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 matrix's row and column indices.

In other words, if matrix[i][j] contains some value, then in the transposed matrix, that same value will be at transpose[j][i].

Input & Output

Example 1 — Basic Rectangle Matrix
$ Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
💡 Note: The transpose flips over the main diagonal: element at (0,0)=1 stays, (0,1)=2 moves to (1,0), (0,2)=3 moves to (2,0), etc.
Example 2 — Square Matrix
$ Input: matrix = [[1,2],[3,4]]
Output: [[1,3],[2,4]]
💡 Note: In a 2×2 matrix: (0,1) and (1,0) elements swap positions while diagonal elements (0,0) and (1,1) remain in place.
Example 3 — Single Row
$ Input: matrix = [[1,2,3,4]]
Output: [[1],[2],[3],[4]]
💡 Note: A 1×4 matrix becomes a 4×1 matrix - the row becomes a column.

Constraints

  • 1 ≤ matrix.length ≤ 1000
  • 1 ≤ matrix[i].length ≤ 1000
  • -109 ≤ matrix[i][j] ≤ 109

Visualization

Tap to expand
Transpose Matrix INPUT Original Matrix (2x3) 1 2 3 4 5 6 col 0 col 1 col 2 r0 r1 matrix = [[1,2,3], [4,5,6]] Rows: 2, Columns: 3 matrix[row][col] e.g. matrix[0][2] = 3 e.g. matrix[1][0] = 4 ALGORITHM STEPS 1 Get Dimensions rows=2, cols=3 2 Create New Matrix size: cols x rows (3x2) 3 Swap Indices result[j][i] = matrix[i][j] 4 Return Result Transposed 3x2 matrix Index Mapping: [0][0]=1 --> [0][0]=1 [0][1]=2 --> [1][0]=2 [0][2]=3 --> [2][0]=3 [1][0]=4 --> [0][1]=4 [1][1]=5 --> [1][1]=5 [1][2]=6 --> [2][1]=6 FINAL RESULT Transposed Matrix (3x2) r0 r1 r2 col 0 col 1 1 4 2 5 3 6 output = [[1,4], [2,5],[3,6]] OK - Complete! Rows: 3, Columns: 2 Time: O(m*n) | Space: O(m*n) Key Insight: Transposing swaps rows and columns. Element at position [i][j] moves to [j][i]. The new matrix dimensions become (original columns) x (original rows). Simply iterate and copy with swapped indices. TutorialsPoint - Transpose Matrix | Optimal Solution
Asked in
Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen