Skip to content

867. Transpose Matrix 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  vector<vector<int>> transpose(vector<vector<int>>& A) {
    vector<vector<int>> ans(A[0].size(), vector<int>(A.size()));

    for (int i = 0; i < A.size(); ++i)
      for (int j = 0; j < A[0].size(); ++j)
        ans[j][i] = A[i][j];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int[][] transpose(int[][] A) {
    int[][] ans = new int[A[0].length][A.length];

    for (int i = 0; i < A.length; ++i)
      for (int j = 0; j < A[0].length; ++j)
        ans[j][i] = A[i][j];

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def transpose(self, A: list[list[int]]) -> list[list[int]]:
    ans = [[0] * len(A) for _ in range(len(A[0]))]

    for i in range(len(A)):
      for j in range(len(A[0])):
        ans[j][i] = A[i][j]

    return ans