Transpose Matrix LeetCode

 Problem Link:

https://leetcode.com/problems/sum-of-beauty-in-the-array/

(It is also problem of day for 02-06-2022)


Solution:


class Solution {

    public int[][] transpose(int[][] matrix) {

        /*

        int t[][]=new int[matrix[0].length][matrix.length];

        for(int i=0;i<matrix.length;i++){

         for(int j=0;j<matrix[0].length;j++){

                t[j][i]=matrix[i][j];

            }

        }

        return t;

        */

        int a=matrix.length;

        int b=matrix[0].length;

        int t[][]=new int[b][a];

        for(int i=0;i<a;i++){

         for(int j=0;j<b;j++){

                t[j][i]=matrix[i][j];

            }

        }

        return t;

        

    }

}


Time Complexity:O(Matrix.length*Matrix[0].length)[LeetCode Time:1ms faster than 52.16%]

Space  Complexity:O(Matrix.length*Matrix[0].length)

Auxiliary Space:O(Matrix[0].length*Matrix.length)[LeetCode Memory:48.4Mb less than 57.35Mb]


Approach Used:


Traverse the arrray and store the value one by one in another array.

The other array will have size m*n if the original array has size n*m.


Question: If we are given a square matrix then is there any other efficient approach also?

Answer: Yes. If you are given with square matrix then an efficient approach will be:


class Solution {

    public int[][] transpose(int[][] matrix) {

        for(int i=0;i<matrix.length;i++){

            for(int j=0;j<i+1;j++){

                int a=matrix[i][j];

                int b=matrix[j][i];

                matrix[j][i]=a;

                matrix[i][j]=b; 

            }

        }

        return matrix;

    }

}


Traversing till diagonal elements of each row of the left half of matrix and then swapping with the corresponding position of another half of matrix.

eg: like traversing (i,j) then swapping this value in the same matrix with the element at (j, i)


The only thing is it can be used in the square matrix only, not the matrix of different sizes of columns and rows because at that time diagonal position will be different and the half distribution of the matrix will also be different. For that case, we will use the above-described approach.


Total Test Cases:36



"Thanks For Reading.😇"

"Share Further To Increase Knowledge Treasure.😊"


Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks