Similar Problems

Similar Problems not available

Transpose Matrix - Leetcode Solution

Companies:

  • adobe
  • amazon

LeetCode:  Transpose Matrix Leetcode Solution

Difficulty: Easy

Topics: matrix array simulation  

Problem Description: Leetcode Problem No. 867 - Transpose Matrix

Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices of the matrix.

Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2: Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]

Solution: To solve this problem, we need to perform a few simple steps:

  1. Get the number of rows and columns of the given matrix.
  2. Create a new 2D matrix of size equal to the transpose of the given matrix (i.e., interchange the number of rows and columns of the given matrix).
  3. Loop through the rows and columns of the given matrix and copy the elements to the corresponding row and column of the new matrix.

Here's the Python code for the solution:

def transpose(matrix):
    rows, cols = len(matrix), len(matrix[0])
    transpose_matrix = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
    return transpose_matrix

In the above code, we first get the number of rows and columns of the given matrix using the len() function. We then create a new 2D matrix of size [cols][rows] (i.e., interchanging the number of rows and columns of the given matrix).

We then loop through the rows and columns of the given matrix using nested for loops. In each iteration, we copy the element at the current row and column of the given matrix to the corresponding column and row of the new matrix.

Finally, we return the new matrix as the transpose of the given matrix.

This solution has a time complexity of O(rowscols), as we need to traverse through each element of the matrix. It also has a space complexity of O(colsrows), as we are creating a new matrix to store the transpose of the given matrix.

Transpose Matrix Solution Code

1