Basic matrix algebra solution using java/JavaScript

  • 0

    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
    after transpose the matrix will become
    Step 2:-
    As in the above matrix example now if we reverse the columns order of the matrix, that will be the answer.

    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];
    // Below loop will reverse the columns order of given matrix 
        for(let r=0 ;r<size;r++){
            let l=0,h=size-1;
                  let temp=matrix[r][l];

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

Log in to reply

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