Transpose of a Matrix

Easy
0/40
Average time to solve is 15m
profile
Contributed by
9 upvotes
Asked in companies
OracleZSPolicyBazaar.com

Problem statement

You are given a matrix ‘MAT’. Print and return the transpose of the matrix. The transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of a matrix A[][] is obtained by changing A[i][j] to A[j][i].

For example:
Let matrix be : 
1 2
3 4

Then transpose of the matrix will be: 
1 3
2 4
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of input contains an integer ‘T’, denoting the number of test cases.

The first line of each test case contains two space-separated integers, ‘M’ and ‘N’, representing the size of the matrices.

The next ‘M’  lines of each test case contain ‘N’ space-separated integers, representing the elements of ‘MAT’.
Output Format :
For each test case, print the transpose of the matrix.

Print output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function. 
Constraints :
1 <= T <= 10
1 <= M, N <= 3*10^3
0 <= MAT[i][j] <= 10^7

Time Limit: 1 sec
Sample Input 1 :
2
2 2
1 2
3 4
3 2
1 2 
2 3
3 4
Sample Output 1 :
1 3
2 4
1 2 3
2 3 4
Explanation For Sample Input 1 :
For test case 1: 
The transpose of the matrix will be: 
1 3
2 4

For test case 2:    
The transpose of the matrix will be: 
1 2 3
2 3 4
Sample Input 2 :
2
2 3
1 2 3 
3 4 5
2 1
1
2
Sample Output 2 :
1 3
2 4 
3 5
1 2
Hint

Try to create a new matrix.

Approaches (1)
Brute-Force Approach

The basic idea is to create a new matrix with the position of elements different than the original matrix. An element at position (‘i’, ‘j’) will lie at position (‘j’, ‘i’) in the transpose of the matrix. So we simply create a new matrix with the position of elements changed.

 

Here is the algorithm :

 

  1. Create a 2-D matrix(say, ‘transMAT’) of size ‘N’ and ‘M’ that will store the transpose of the matrix.
  2. Run a loop from 0 to ‘N’ (say, iterator ‘i’) to traverse all the rows.
    • Run a loop from 0 to ‘M’ (say, iterator ‘j’) to traverse all the columns
      • Update ‘transMAT[i][j]’ with ‘MAT[j][i]’.
  3. Return ‘transMAT’.
Time Complexity

O(M*N), where ‘M’ and ‘N’ are the size of the matrix.
 

We traverse all the cells of both the matrices only once. Therefore, the overall time complexity will be O(M*N).

Space Complexity

O(M*N), where ‘M’ and ‘N’ are the size of the matrix.

 

We use a matrix to store the transpose. Therefore, the overall space complexity will be O(M*N).

Code Solution
(100% EXP penalty)
Transpose of a Matrix
Full screen
Console