DEV Community

Debesh P.
Debesh P.

Posted on

Transpose of Matrix | GeeksforGeeks‬ Beginner's DSA Sheet | Full Solution Explained | With Source Code

hola coders!

In this video, I directly solve a problem on the transpose of a matrix—no unnecessary theory, just straight to the point :)


Problem Link: https://www.geeksforgeeks.org/problems/transpose-of-matrix-1587115621/1

Source Code: https://github.com/debeshp6/Gfg-Tutorials/blob/main/TransposeOfMatrix.java


Code

class Solution {
    public void transpose(int n, int mat[][]) {

        // mat[][] is a 2D array here
        // n is the array length
        // let's start!

        for(int i=0; i<n; i++) { // first iteration
            for(int j=i+1; j<n; j++) { // second iteration
                int temp = mat[i][j]; // here we are simply swapping the values using a third 'temp' variable
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n^2)

Have questions or doubts? Drop them in the comments, and I'll be happy to help!

Top comments (0)