# Basic matrix algebra solution using java/JavaScript

• Complexity: O(n^2)
Space Complexity:O(1)

This problem can be solved by the basic matrix algebra, below is the two-step solution.

Step 1: Transpose of a matrix
the transpose of a matrix is when we exchange the row and column of a matrix. this will give as the matrix rotated by 90 degrees, but for the final solution, we will need to reverse the order of columns.

for example below is the given matrix
`[[1,2,3],`
`[4,5,6],`
`[7,8,9]]`
after transpose the matrix will become
`[[1,4,7],`
`[2,5,8],`
`[3,6,9]]`
Step 2:-
As in the above matrix example now if we reverse the columns order of the matrix, that will be the answer.
`[[7,4,1],`
`[8,5,2],`
`[9,6,3]]`

below is the complete solution to this problem

``````var rotate = function(matrix) {

// take transpose of matrix
var size=matrix.length;
// This for loop will transpose the given matrix
for(let i=0;i<size;i++){ //row
for(let j=i;j<size;j++){
let temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}

}

// Below loop will reverse the columns order of given matrix
for(let r=0 ;r<size;r++){
let l=0,h=size-1;
while(l<h){
let temp=matrix[r][l];
matrix[r][l]=matrix[r][h];
matrix[r][h]=temp;
l++;
h--;
}
}
};
``````

Hope this will be helpful for you.
Happy Learning .....

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.