Solution: Transpose Matrix

Let’s solve the Transpose Matrix problem using the Matrices pattern.

Statement

Given a matrix represented as a 2D integer list, return its transpose. The transpose of a matrix is obtained by swapping its rows with its columns or vice versa.

Constraints:

  • 11 \leq m, n 100\leq 100

  • 104-10^4 \leq matrix[i][j] 104\leq 10^4

Solution

The idea is to calculate the transpose of a given matrix by swapping its rows with columns. The matrix is flipped over, converting the first row into the first column, the second row into the second column, and so forth. The result is a new matrix in which the element at the position (i, j)(i,~j) in the original matrix is now located at the position (j, i)(j,~i) in the transposed matrix.

Here’s the step-by-step implementation of the solution:

  • Start by calculating the number of rows and columns in the original matrix.

  • A new matrix, result, is initialized with dimensions columns x rows.

  • Iterate over each element of the original matrix row-wise using a nested loop.

    • The outer loop runs over each row i of the original matrix.

    • The inner loop runs over each column j.

    • During each iteration, the element at position [i][j] in the original matrix is placed in position [j][i] in the result matrix.

  • The result matrix, which now holds the transposed version of the original matrix, is returned after all elements have been processed.

Let’s look at the following illustration to get a better understanding of the solution:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.