Transpose Matrix
Problem
Given a 2D integer array matrix, return its transpose. The transpose flips the matrix over its main diagonal, swapping row and column indices: the element at row i, column j moves to row j, column i.
matrix = [[1,2,3],[4,5,6]][[1,4],[2,5],[3,6]]def transpose(matrix):
rows, cols = len(matrix), len(matrix[0])
res = [[0] * rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
res[j][i] = matrix[i][j]
return res
function transpose(matrix) {
const rows = matrix.length, cols = matrix[0].length;
const res = Array.from({ length: cols }, () => new Array(rows));
for (let i = 0; i < rows; i++)
for (let j = 0; j < cols; j++)
res[j][i] = matrix[i][j];
return res;
}
int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] res = new int[cols][rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
res[j][i] = matrix[i][j];
return res;
}
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
vector<vector<int>> res(cols, vector<int>(rows));
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
res[j][i] = matrix[i][j];
return res;
}
Explanation
The transpose of a grid just flips it over its main diagonal: whatever sits at row i, column j ends up at row j, column i. Rows turn into columns and columns turn into rows.
The code first makes a fresh empty grid res with swapped dimensions: if the input is rows tall and cols wide, then res is cols tall and rows wide.
Then two simple loops visit every cell of the original. For each one it copies the value straight across with res[j][i] = matrix[i][j] — notice the indices are swapped on the two sides.
Example: matrix = [[1,2,3],[4,5,6]] is 2×3. The value 2 lives at row 0, column 1, so it moves to row 1, column 0. After all cells move, you get [[1,4],[2,5],[3,6]], a 3×2 grid.
It works because every cell is copied exactly once to its mirrored spot, so the new grid is a perfect flipped copy.