Problem Description
Given a 2D integer array matrix, return the transpose of matrix. The transpose is obtained by flipping the matrix over its main diagonal, thereby switching the matrix's row and column indices.
Key Insights
- The value at position (i, j) in the original matrix moves to (j, i) in the transposed matrix.
- The transposed matrix dimensions are the reverse of the original: if the original is m x n, then the transposed is n x m.
- A simple double loop is sufficient to swap the indices, ensuring O(m*n) time complexity.
- This problem handles both square and rectangular matrices.
Space and Time Complexity
Time Complexity: O(mn)
Space Complexity: O(mn) for the new matrix holding the transposed values
Solution
The solution involves iterating over each element of the original matrix and assigning it to the corresponding position in the new matrix where the indexes are swapped. We create the transposed matrix with dimensions based on the number of columns and rows of the original matrix, respectively. The approach leverages basic array manipulation with nested loops to fill in the new matrix.