Leetcode 867 - Transpose Matrix

Problem Statement

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it’s main diagonal, switching the row and column indices of the matrix.

Example 1:

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

Example 2:

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

Note:

1 <= A.length <= 1000
1 <= A[0].length <= 1000

Solution

1
2
3
4
5
6
7
8
9
class Solution:
def transpose(self, A):
rows = [[] for _ in range(len(A[0]))]
for i in range(len(rows)):
for k in range(len(A)):
rows[i].append(A[k][i])
return rows

Time: O(R C) in A
Space: O(R
C) in A’s transpose

Explanation

Start by creating the result matrix which is made up of a list of lists; there will be len(A[0]) of them. Loop through each row and start appending each column value to the row. Finally return the rows. Alternatively, Python has this one liner solution:

1
2
3
class Solution:
def transpose(self, A):
return list(zip(*A))

What zip does is that if you have [1,2,3],[4,5,6],[7,8,9] then it will create a result for each column as a list so you get the final transpose. *A basically takes a list of lists and separates it out so you’re looking at zip([1,2,3],[4,5,6],[7,8,9]). It’s pretty neat, but supposedly these kind of pythonic solutions are looked down upon in interviews, so try to avoid them. But good to have in your backpocket, just in case.