Leetcode 867: Transpose Matrix

grid47
grid47
Exploring patterns and algorithms
Aug 12, 2024 5 min read

Given a 2D integer array matrix, return its transpose. The transpose of a matrix is formed by flipping the matrix over its main diagonal, converting rows into columns and columns into rows.
Problem
Approach
Steps
Complexity
Input: The input is a 2D integer array `matrix` of dimensions `m x n`.
Example: Input: matrix = [[2, 4], [6, 8], [10, 12]]
Constraints:
• m == matrix.length
• n == matrix[i].length
• 1 <= m, n <= 1000
• 1 <= m * n <= 10^5
• -10^9 <= matrix[i][j] <= 10^9
Output: Return a 2D integer array representing the transpose of the given matrix.
Example: Output: [[2, 6, 10], [4, 8, 12]]
Constraints:
• The dimensions of the output matrix will be `n x m`.
• Each element of the output is obtained by swapping rows and columns of the input matrix.
Goal: Transform the input matrix by swapping its rows and columns.
Steps:
• Determine the dimensions `m` and `n` of the input matrix.
• Create a new matrix of dimensions `n x m` initialized with zero values.
• Iterate over each element in the input matrix, assigning `matrix[i][j]` to `transpose[j][i]`.
• Return the newly formed transposed matrix.
Goal: Ensure the solution meets the problem requirements efficiently.
Steps:
• Handle large matrices with up to 10^5 elements efficiently.
• Support negative and large positive integer values in the matrix.
Assumptions:
• The input matrix is non-empty and well-formed.
• All rows of the matrix have the same number of columns.
Input: Input: matrix = [[2, 4], [6, 8], [10, 12]], Output: [[2, 6, 10], [4, 8, 12]]
Explanation: The transpose swaps rows and columns. The first column of the input becomes the first row of the output, and so on.

Input: Input: matrix = [[7]], Output: [[7]]
Explanation: A 1x1 matrix remains the same after transposition.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus