867. Transpose Matrix
Problem Description
Given a 2D integer array matrix
, you need to return the transpose of the matrix.
The transpose of a matrix is obtained by flipping the matrix over its main diagonal. This means that the row and column indices are switched - what was at position (i, j)
in the original matrix will be at position (j, i)
in the transposed matrix.
For example, if you have a matrix with m
rows and n
columns, the transposed matrix will have n
rows and m
columns. Each element at position (i, j)
in the original matrix becomes the element at position (j, i)
in the transposed matrix.
The visual example shows how the first row [1, 2, 3]
becomes the first column in the transposed matrix, the second row [4, 5, 6]
becomes the second column, and so on. The main diagonal (elements where row index equals column index) remains in the same position after transposition.
Intuition
When we think about transposing a matrix, we're essentially converting rows into columns and columns into rows. The first row becomes the first column, the second row becomes the second column, and so on.
If we have a matrix with dimensions m x n
, after transposition it becomes n x m
. The key insight is that the element at position (i, j)
in the original matrix needs to move to position (j, i)
in the transposed matrix. This is like looking at the matrix from a different angle - we're rotating our perspective by 90 degrees along the main diagonal.
To build the transposed matrix, we can create a new matrix with swapped dimensions and systematically copy each element from its original position to its transposed position. For each row i
and column j
in the original matrix, we place that element at row j
and column i
in the new matrix.
In Python, there's an elegant way to achieve this using the zip(*matrix)
pattern. The *
operator unpacks the rows of the matrix as separate arguments to zip
. The zip
function then takes the first element from each row to form the first tuple, the second element from each row to form the second tuple, and so on. This effectively groups elements by their column index, which is exactly what we want for transposition - each column becomes a new row in the transposed matrix.
Solution Approach
Following the simulation approach, we need to create a new matrix where each element at position (i, j)
in the original matrix is placed at position (j, i)
in the transposed matrix.
Let m
be the number of rows and n
be the number of columns in the input matrix. The transposed matrix will have dimensions n x m
.
The implementation uses Python's zip(*matrix)
to achieve the transpose:
-
Unpacking the matrix: The
*matrix
syntax unpacks the rows of the matrix as individual arguments. Ifmatrix = [[1,2,3], [4,5,6]]
, then*matrix
expands to[1,2,3], [4,5,6]
. -
Applying zip: The
zip()
function takes these unpacked rows and pairs up elements at the same index position from each row. It creates tuples where:- The first tuple contains all first elements:
(1, 4)
- The second tuple contains all second elements:
(2, 5)
- The third tuple contains all third elements:
(3, 6)
- The first tuple contains all first elements:
-
Converting to list: Since
zip()
returns an iterator of tuples, we uselist()
to convert it to a list of lists (though technically it's a list of tuples, which works the same way for our purposes).
This elegantly handles the index swapping for us - what were columns (same index across different rows) become rows in the result. The time complexity is O(m * n)
since we need to visit each element once, and the space complexity is also O(m * n)
for storing the transposed matrix.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through transposing a small matrix step by step:
Input: matrix = [[1, 2, 3], [4, 5, 6]]
This is a 2×3 matrix (2 rows, 3 columns). After transposition, we expect a 3×2 matrix (3 rows, 2 columns).
Step 1: Unpack the matrix
When we use *matrix
, it unpacks the rows:
- First row:
[1, 2, 3]
- Second row:
[4, 5, 6]
Step 2: Apply zip function
zip([1, 2, 3], [4, 5, 6])
pairs up elements at the same index:
- Index 0: Takes
1
from first row and4
from second row →(1, 4)
- Index 1: Takes
2
from first row and5
from second row →(2, 5)
- Index 2: Takes
3
from first row and6
from second row →(3, 6)
Step 3: Convert to list
The result becomes: [[1, 4], [2, 5], [3, 6]]
Verification: Let's verify the transpose is correct by checking the index mapping:
- Original
matrix[0][0] = 1
→ Transposedresult[0][0] = 1
✓ - Original
matrix[0][1] = 2
→ Transposedresult[1][0] = 2
✓ - Original
matrix[0][2] = 3
→ Transposedresult[2][0] = 3
✓ - Original
matrix[1][0] = 4
→ Transposedresult[0][1] = 4
✓ - Original
matrix[1][1] = 5
→ Transposedresult[1][1] = 5
✓ - Original
matrix[1][2] = 6
→ Transposedresult[2][1] = 6
✓
The first row [1, 2, 3]
has become the first column, and the second row [4, 5, 6]
has become the second column, which is exactly what transposition should achieve.
Solution Implementation
1class Solution:
2 def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
3 # Use zip with unpacking operator (*) to transpose the matrix
4 # *matrix unpacks all rows as separate arguments to zip
5 # zip then combines elements at the same index from each row into tuples
6 # This effectively swaps rows and columns
7 transposed = zip(*matrix)
8
9 # Convert the zip object to a list of lists
10 # zip returns tuples, so we need to convert each tuple to a list
11 return [list(row) for row in transposed]
12```
13
14Alternative implementation without using zip:
15```python3
16class Solution:
17 def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
18 # Get dimensions of the original matrix
19 rows = len(matrix)
20 cols = len(matrix[0]) if rows > 0 else 0
21
22 # Create a new matrix with swapped dimensions
23 # Original matrix[i][j] becomes result[j][i]
24 result = [[matrix[i][j] for i in range(rows)] for j in range(cols)]
25
26 return result
27
1class Solution {
2 /**
3 * Transposes a given matrix by swapping rows and columns.
4 * The element at position [i][j] becomes the element at position [j][i].
5 *
6 * @param matrix The input 2D array to be transposed
7 * @return A new 2D array representing the transposed matrix
8 */
9 public int[][] transpose(int[][] matrix) {
10 // Get dimensions of the original matrix
11 int rows = matrix.length;
12 int columns = matrix[0].length;
13
14 // Create result matrix with swapped dimensions (columns x rows)
15 int[][] transposedMatrix = new int[columns][rows];
16
17 // Iterate through each position in the transposed matrix
18 for (int i = 0; i < columns; i++) {
19 for (int j = 0; j < rows; j++) {
20 // Swap row and column indices:
21 // Element at matrix[j][i] goes to transposedMatrix[i][j]
22 transposedMatrix[i][j] = matrix[j][i];
23 }
24 }
25
26 return transposedMatrix;
27 }
28}
29
1class Solution {
2public:
3 vector<vector<int>> transpose(vector<vector<int>>& matrix) {
4 // Get dimensions of the original matrix
5 int numRows = matrix.size();
6 int numCols = matrix[0].size();
7
8 // Create result matrix with swapped dimensions (n x m becomes m x n)
9 vector<vector<int>> result(numCols, vector<int>(numRows));
10
11 // Iterate through each position in the transposed matrix
12 for (int row = 0; row < numCols; ++row) {
13 for (int col = 0; col < numRows; ++col) {
14 // Swap row and column indices from original matrix
15 result[row][col] = matrix[col][row];
16 }
17 }
18
19 return result;
20 }
21};
22
1/**
2 * Transposes a given matrix (swaps rows and columns)
3 * @param matrix - The input 2D array to be transposed
4 * @returns The transposed matrix where matrix[i][j] becomes result[j][i]
5 */
6function transpose(matrix: number[][]): number[][] {
7 // Get dimensions of the input matrix
8 const rowCount: number = matrix.length;
9 const columnCount: number = matrix[0].length;
10
11 // Initialize the result matrix with swapped dimensions (n x m becomes m x n)
12 const transposedMatrix: number[][] = Array.from(
13 { length: columnCount },
14 () => Array(rowCount).fill(0)
15 );
16
17 // Iterate through each position in the transposed matrix
18 for (let row = 0; row < columnCount; row++) {
19 for (let column = 0; column < rowCount; column++) {
20 // Swap the row and column indices from the original matrix
21 transposedMatrix[row][column] = matrix[column][row];
22 }
23 }
24
25 return transposedMatrix;
26}
27
Time and Space Complexity
The time complexity is O(m × n)
, where m
is the number of rows and n
is the number of columns in the matrix. This is because transposing a matrix requires visiting every element exactly once to construct the transposed result, regardless of whether using zip(*matrix)
or a traditional nested loop approach.
The space complexity is O(m × n)
for the output space needed to store the transposed matrix. However, if we exclude the space required for the output (as mentioned in the reference answer), the auxiliary space complexity is O(1)
, since the zip(*matrix)
operation uses iterators and doesn't create additional intermediate data structures proportional to the input size.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Confusing In-Place Transposition with General Transposition
A common mistake is attempting to transpose a non-square matrix in-place. While square matrices (n×n) can be transposed in-place by swapping elements across the diagonal, rectangular matrices (m×n where m≠n) cannot be transposed in-place because the dimensions change.
Incorrect approach for non-square matrices:
# This ONLY works for square matrices!
def transpose(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return matrix
Solution: Always create a new matrix for the transpose unless you're certain you're dealing with square matrices:
def transpose(matrix):
rows, cols = len(matrix), len(matrix[0])
result = [[0] * rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
result[j][i] = matrix[i][j]
return result
2. Incorrectly Initializing the Result Matrix
When manually creating the transposed matrix, a frequent error is using the wrong dimensions or sharing references between rows.
Incorrect initialization:
# Wrong dimensions - keeps original dimensions
result = [[0] * cols for _ in range(rows)] # Should be swapped!
# Shared reference problem
result = [[0] * rows] * cols # All rows reference the same list!
Solution: Ensure dimensions are swapped (cols × rows becomes the new size) and each row is independently created:
result = [[0] * rows for _ in range(cols)] # Correct dimensions
# OR use list comprehension that creates new lists
result = [[matrix[i][j] for i in range(rows)] for j in range(cols)]
3. Edge Case Handling with Empty Matrices
Failing to handle empty matrices or matrices with empty rows can cause index errors.
Problematic code:
def transpose(matrix):
cols = len(matrix[0]) # IndexError if matrix is empty
# ...
Solution: Check for empty matrices before accessing elements:
def transpose(matrix):
if not matrix or not matrix[0]:
return []
rows, cols = len(matrix), len(matrix[0])
# ... rest of the implementation
How many ways can you arrange the three letters A, B and C?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!