Coding Interview Prep: The Transpose Matrix Problem

Moeedlodhi
2 min readNov 15, 2023

Let’s get started with this

Problem Statement:

Create a function that takes a 2D array of integers, matrix, as input and outputs it transpose. The transpose of a matrix involves swapping its rows and columns across the main diagonal, which runs from the top-left to the bottom-right. It's guaranteed that the input matrix has at least one value, but its dimensions (width and height) may differ.

So for those who are aware of matrices, this shouldn't require too much explaining. But to summarize, We just need to take in a matrix and output its transpose. For example:

matrix = [
[1, 2],
[3, 4],
[5, 6]
]

tranpose = [
[1, 3, 5],
[2, 4, 6]
]

The “matrix” has 3 arrays of length 2 each. The transpose has 2 arrays of length 3 each. That’s a “transpose”.

Test cases

test_cases = [{
"matrix": [
[1],
[-1]
],
"transpose": [
[1, -1]
],
{
"matrix": [
[1, 2, 3]
],
"transpose": [
[1],
[2],
[3]
]
},
{
"matrix": [
[5, 6, 3, -3, 12],
[-3, 6, 5, 2, -1],
[0, 0, 3, 12, 3]
],
"transpose": [
[5, -3, 0],
[6, 6, 0],
[3, 5, 3],
[-3, 2, 12],
[12, -1, 3]
]}
}]

My Solution:

def transposeMatrix(matrix):
# Write your code here.
number_of_matrices = len(matrix)
length_of_one_matric = len(matrix[0])
number_of_arrays = [[] for i in range(0,length_of_one_matric)]
for matric in matrix:
for index,array in enumerate(number_of_arrays):
array.append(matric[index])

return number_of_arrays

Enjoyed reading this feel free to give it a like for that helps me out a lot. Till we meet again.

--

--