# Inplace MxN size matrix transpose

Matrix transposition is a fundamental operation in linear algebra that involves swapping rows and columns of a matrix. In this Article, we will explore the concept of in-place matrix transposition for matrices of size m x n, and provide a detailed explanation along with Java code to implement this operation.

Understanding In-Place Matrix Transposition

Matrix transposition involves interchanging rows and columns of a matrix. For an m x n matrix, the transposed matrix will have dimensions n x m. In the context of in-place transposition, we aim to achieve this transposition without using additional memory space for a new matrix. Instead, we will manipulate the existing matrix elements to achieve the transposed form.

Algorithm for In-Place Matrix Transposition

The algorithm for in-place matrix transposition can be summarized in the following steps:

• Iterate through each element (i, j) in the matrix where 0 <= i < m and 0 <= j < n.
• Swap the element at (i, j) with the element at (j, i).

By following this algorithm, we ensure that each element is swapped with its corresponding element across the main diagonal of the matrix.

Here's a step-by-step breakdown of the Java code implementing the in-place matrix transposition algorithm:

Output:

Step by step Explanation of the above code:

1. The transpose method takes a 2D array (matrix) as its parameter and performs the in-place transposition.
2. The printMatrix method is used to display the matrix.
3. In the main method, we create an example 3x3 matrix and demonstrate the transposition operation.
4. The nested loops in the transpose method iterate through the matrix. The inner loop iterates through elements in the row starting from i+1 to the end. This avoids swapping elements twice.
5. Swapping is performed using a temporary variable temp, which ensures the elements are exchanged without loss of data.

Time Complexity of the entire code: O(n^2 + m * n)

Let's brake down the time complexity for better understanding

• The most significant factor in the time complexity is the nested loop that iterates through the matrix to perform the in-place transposition. The outer loop runs for m times (number of rows), and the inner loop runs for n - i - 1 times (number of remaining columns after i), where i is the current row index.
• The printMatrix method iterates through each element of the matrix once to print it. Since there are m rows and n columns, the total number of elements in the matrix is m * n.

Thus, the time complexity of the transpose method is O(n^2+ m * n), where n is the number of columns and m is the number of rows.

Space Complexity of the entire code: O(1)

Since we are not making use of any additional space in order to transpose the matrix since it space complexity would be O(1).