Transpose Matrix | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

The transpose of a matrix is a new matrix whose rows are the columns of the original matrix.

You have given a matrix A, write a program to return the transpose of given matrix A.

Example 

Transpose Matrix

Input :- [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output :- [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Input :- [[1, 2, 3], [4, 5, 6]]
Output :- [[1, 4], [2, 5], [3, 6]]

Solution

Copy the elements of each row of original matrix to each column for result matrix.

Time Complexity: O(R ∗ C), where R and C are the number of rows and columns in the given matrix A.

Space Complexity: O(R ∗ C), where R and C are the number of rows and columns in the given matrix A.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int[][] result = main.transpose(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
		for(int[] array : result) {
			for(int i : array) {
				System.out.print(i + ", ");
			}
			System.out.println();
		}								
	}
	
	/* Solution */    
	public int[][] transpose(int[][] A) {
        
        int[][] B = new int[A[0].length][A.length];
        
        for(int i=0; i<A.length; i++){
            for(int j=0; j<A[i].length; j++){                
                B[j][i] = A[i][j];               
            }            
        }
        return B;        
    }
}

Result

1, 4, 7, 
2, 5, 8, 
3, 6, 9, 

Similar Post

  1. Relative Ranks
  2. Check if Coordinates make a Straight Line
  3. Design Min Stack Data Structure

That’s all for Transpose Matrix in Java, If you liked it, please share your thoughts in a comments section and share it with others too.