Transpose 2D Matrix in Java - Time & Space Complexity? Here's my algorithm / approach for transposing a 2D Matrix on the main diagonal.

Before: 

a L M d 
b G c N 
H K e F 
I J O P 


After: 

a b H I 
L G K J 
M c e O 
d N F P 




My code:

public class Matrix {

    static String[][] matrix = {

            {"a", "L", "M", "d"},
            {"b", "G", "c", "N"},
            {"H", "K", "e", "F"},
            {"I", "J", "O", "P"}
    };

    public void transpose(String[][] matrix) {
       String[][] transposedArray = new String [4][4];
       for (int row =0; row &lt; 4; row ++) {
           for (int col = 0; col &lt; 4; col++) {
               transposedArray[row][col] = matrix[col][row];  
           }
       }
    }
}


What is the time &amp; space complexity of this approach? 

Is there a better optimal solution?
I have three suggestions for you.


Instead of String, you can use char, less memory footprint than a String.
In the transpose method, I suggest that you return the array, since the method does nothing at the moment.


static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row &lt; 4; row ++) {
      for (int col = 0; col &lt; 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}



Since the matrix variable is static, I suggest that you also put the method static.


Refactored code

public static void main(String[] args) {
   System.out.println(Arrays.deepToString(transpose(matrix)));
}

static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public static char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row &lt; 4; row ++) {
      for (int col = 0; col &lt; 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}