Transpose Matrix — Solution in Python, Java & C++
Transpose Matrix solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and matrix.
Transpose Matrix is an easy coding problem on arrays, matrix and simulation.
- Difficulty: Easy
- Topics: Arrays, Matrix, Simulation
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a 2D integer array matrix, return its transpose — the matrix flipped over its main diagonal, swapping row and column indices.
Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Constraints
1 <= rows, cols <= 8-100 <= matrix[i][j] <= 100
Hints for Transpose Matrix
Hint 1
The transposed matrix has dimensions cols × rows.
Hint 2
out[j][i] = matrix[i][j].
How to solve Transpose Matrix
Transposing swaps the roles of the two indices: the value at row i, column j becomes the value at row j, column i. The only wrinkle is that the result has the opposite dimensions — a rows × cols matrix transposes to cols × rows — so it cannot be done in place unless the matrix is square.
Approach
- Read the dimensions
rowsandcolsfrom the input. - Allocate the output with
colsrows androwscolumns. - For every
iandj, writeout[j][i] = matrix[i][j]. - Return the new matrix.
Why it works
The transpose is defined entrywise, so a single pass over every cell is both necessary and sufficient — there is no structure to exploit and no way to avoid touching each value once. Building a fresh matrix sidesteps the aliasing problem: an in-place swap only works when the shape is preserved, which is to say only for square matrices.
Complexity
- Time —
O(rows · cols) - Space —
O(rows · cols) for the output
Pitfalls
- The output dimensions are swapped — allocating
rows × colsoverflows or truncates for non-square input. - Write
out[j][i], notout[i][j]; the latter just copies the matrix. - In-place transposition is only valid for square matrices, and even then must swap only one triangle or it undoes itself.
Reference solution
Python
from typing import List
def transpose(matrix: List[List[int]]) -> List[List[int]]:
return [list(row) for row in zip(*matrix)]Java
public static int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] out = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) out[j][i] = matrix[i][j];
}
return out;
}C++
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int rows = (int) matrix.size(), cols = (int) matrix[0].size();
vector<vector<int>> out(cols, vector<int>(rows, 0));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) out[j][i] = matrix[i][j];
}
return out;
}JavaScript
var transpose = function(matrix) {
const rows = matrix.length, cols = matrix[0].length;
const out = [];
for (let j = 0; j < cols; j++) {
const row = [];
for (let i = 0; i < rows; i++) row.push(matrix[i][j]);
out.push(row);
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Matrix and Grid Traversal