Java solution for finding the transpose of a matrix
Introduction
A transpose of a matrix is a new matrix formed by exchanging rows with columns. In this leetcode problem, we will find the transpose of a matrix.
Problem
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]]
Solution
- If the input matrix is of size ROW, COL then the Transpose matrix would be of size of ROW=COL & COL=ROW.
- The location of elements in the transpose matrix will be inverted as well, which means if the element in the input matrix is at i, j then in the transpose matrix it would be j, i.
so, transpose[col][row]=matrix[row][col]
class Solution {
public int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int 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;
}
}
Results
- Our solution is accepted and it’s pretty efficient.
Complexity
Time complexity:
time complexity is O(N²) since we are iterating over each element.
Space complexity:
space complexity is O(N), and N is the size of the input matrix for the result matrix.
Conclusion
In this problem, we learned about the 2D matrix and the transpose of a matrix. Time complexity is O(N²) and space complexity is O(N).
Before You Leave
- Crack DSA interview with Mastering Leetcode In Java — Top 100 Most Asked Problems
- Crack SQL Interview With Grokking the SQL Interview [Free Sample Copy]
- Subscribe to Java Newsletter to keep up with all the updates in Java/Spring world.