Given a 2D integer array
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Output: [[1,4,7],[2,5,8],[3,6,9]]
Output: [[1,4],[2,5],[3,6]]
Constraints:
m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 1 <= m * n <= 105 -109 <= matrix[i][j] <= 109
Contents
Solution 1 - Convert rows to columns
In this approach, we will simply convert
Implementation steps:
-
Create a variable
result 2D array with rows length as columns length input array, and columns length as rows length input array. -
Then, loop through for each row
i and columnj of input arraymatrix , add the value to rowj and columni ofresult array.
Complexity Analysis:
Time complexity: Above code runs in O(m * n) time where
Space complexity: O(m * n) for the result array.
Above implementations source code can be found at