Leetcode 867. Transpose Matrix

Problem Explanation

The problem is to write a program that receives a matrix A and returns its transpose. The transpose of a matrix is a new matrix whose rows are the columns of the original. This is done by flipping the matrix over its main diagonal.
In matrix representation, the process of creating a new matrix 'Transpose' from a given matrix 'A' such that the rows of 'A' become the columns of 'Transpose' and vice versa.

Let’s take a look at an example:

Input: [[1,2,3],[4,5,6],[7,8,9]]

In this case, the input matrix A is:

1    1 2 3
2    4 5 6
3    7 8 9

When we take the transpose of A, each row become a column.

Output: [[1,4,7],[2,5,8],[3,6,9]]

So the output matrix will be:

1    1 4 7
2    2 5 8
3    3 6 9

Approach

A simple approach is to create a new matrix and copy over the elements from the original matrix to the new one in a transposed order.

  1. We initialize a new matrix of size (number of columns in A, number of rows in A).

  2. We loop over each element in the original matrix, and place it in the new matrix at the transposed position. The transposed position of an element at position (i, j) in the original matrix is (j, i) in the new matrix.

C++ Solution

1
2cpp
3class Solution {
4public:
5    vector<vector<int>> transpose(vector<vector<int>>& A) {
6        vector<vector<int>> ans(A[0].size(), vector<int>(A.size())); // Step 1
7
8        for (int i = 0; i < A.size(); ++i) { // Step 2
9            for (int j = 0; j < A[0].size(); ++j) {
10                ans[j][i] = A[i][j];
11            }
12        }
13        
14        return ans;
15    }
16};

Python Solution

1
2python
3class Solution:
4    def transpose(self, A: List[List[int]]) -> List[List[int]]:
5        return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]

Java Solution

1
2java
3class Solution {
4    public int[][] transpose(int[][] A) {
5        int[][] result = new int[A[0].length][A.length];
6        for (int i = 0; i < A.length; i++)
7            for (int j = 0; j < A[0].length; j++)
8                result[j][i] = A[i][j];
9        return result;
10    }
11}

Javascript Solution

1
2javascript
3var transpose = function(A) {
4    return A[0].map((col, i) => A.map(row => row[i]));
5};

C# Solution

1
2csharp
3public class Solution {
4    public int[][] Transpose(int[][] A) {
5        int[][] result = new int[A[0].Length][];
6        for (int i = 0; i < A[0].Length; i++) {
7            result[i] = new int[A.Length];
8            for (int j = 0; j < A.Length; j++)
9                result[i][j] = A[j][i];
10        }
11        return result;
12    }
13}

Explanation of Solutions

In the solution code for each programming language, we first get the dimensions of the matrix A. This is done to create a new matrix with switched x and y dimensions. If A is an m x n matrix, its transpose matrix will be n x m dimensions.

In C++, we first create a new matrix 'ans' and then loop over A, setting ans[j][i] = A[i][j]. The use of vector<vector> helps us creating a dynamic 2D array in C++, where the size is not fixed and can be changed.

In the Python solution, a simpler, more concise approach is taken, making use of Python's powerful list comprehension capabilities. The solution loops over each column index in the first row of A, and constructs a new row for the transposed matrix for each column. The new row is created by getting the elements at the column index for every row in the original matrix.

In the Java, JavaScript, and C# solutions, we create the new matrix and then fill it in with the appropriate elements from the original matrix. Result[j][i] is set to A[i][j], effectively switching the row and column indices.

Overall, all of these solutions are both time and space efficient, with a time complexity of O(mn) (since every element in the matrix has to be touched once) and a space complexity of O(mn) (since a new matrix of size m*n has to be created to hold the transposed elements).

One potential improvement could be to perform the transpose in place (without creating a new matrix), but this is only possible for square matrices (i.e., matrices where the number of rows equals the number of columns), so it is less generally applicable than the provided solutions.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫