Transpose Matrix - Problem
Given a 2D integer array matrix, return the transpose of the matrix. The transpose of a matrix is created by flipping the matrix over its main diagonal, which means switching the matrix's row and column indices.

In simpler terms, if you have an element at position [i][j] in the original matrix, it will be moved to position [j][i] in the transposed matrix. This operation effectively converts rows into columns and columns into rows.

Goal: Transform the input matrix by swapping rows and columns.
Input: A 2D integer array representing a matrix
Output: A new 2D array representing the transposed matrix

Input & Output

example_1.py — Basic 2x3 Matrix
$ Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
💡 Note: The first row [1,2,3] becomes the first column [1,4], and the second row [4,5,6] becomes the second column. Element at [0][0]=1 moves to [0][0]=1, element at [0][1]=2 moves to [1][0]=2, etc.
example_2.py — Square Matrix
$ Input: matrix = [[1,2],[3,4]]
Output: [[1,3],[2,4]]
💡 Note: In a square matrix, the transpose flips elements across the main diagonal. Element [0][1]=2 swaps with element [1][0]=3.
example_3.py — Single Row Matrix
$ Input: matrix = [[1,2,3,4]]
Output: [[1],[2],[3],[4]]
💡 Note: A single row matrix becomes a single column matrix. Each element becomes its own row in the result.

Visualization

Tap to expand
Original Matrix (2×3)123456TRANSPOSETransposed (3×2)142536Each element at position [i][j] moves to position [j][i]Rows become columns, columns become rows
Understanding the Visualization
1
Identify Dimensions
Original matrix is m×n, result will be n×m
2
Create Result Matrix
Initialize new matrix with swapped dimensions
3
Map Coordinates
Element at [i][j] moves to [j][i]
4
Copy All Elements
Systematically copy each element to its new position
Key Takeaway
🎯 Key Insight: Matrix transpose is simply a coordinate transformation where [i][j] → [j][i]. The algorithm is optimal because every element must be copied exactly once.

Time & Space Complexity

Time Complexity
⏱️
O(m×n)

We need to visit each element exactly once, where m and n are the dimensions of the matrix

n
2n
Linear Growth
Space Complexity
O(m×n)

We need to create a new matrix to store the transposed result

n
2n
Linearithmic Space

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 1000
  • -109 ≤ matrix[i][j] ≤ 109
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
78.0K Views
Medium Frequency
~8 min Avg. Time
2.4K 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