867. Transpose Matrix LeetCode Solution
In this guide, you will get 867. Transpose Matrix LeetCode Solution with the best time and space complexity. The solution to Transpose Matrix problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Transpose Matrix solution in C++
- Transpose Matrix solution in Java
- Transpose Matrix solution in Python
- Additional Resources
Problem Statement of Transpose Matrix
Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s 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:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Complexity Analysis
- Time Complexity: O(n^2)
- Space Complexity: O(n^2)
867. Transpose Matrix LeetCode Solution in C++
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;
}
};
/* code provided by PROGIEZ */
867. Transpose Matrix LeetCode Solution in Java
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;
}
}
// code provided by PROGIEZ
867. Transpose Matrix LeetCode Solution in Python
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
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.