Transpose Matrix

easy array matrix simulation

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.

Inputmatrix = [[1,2,3],[4,5,6]]
Output[[1,4],[2,5],[3,6]]
A 2×3 matrix becomes a 3×2 matrix.

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;
}
Time: O(rows · cols) Space: O(rows · cols)