# Rotate matrix 90 degrees

I recently did problem 1.7 Rotate Matrix in Cracking the Coding Interview. I realized my code is very different than what is in the book and what I am also fining online (I'm having trouble following the code in the book). I just want to know if the code I wrote would be appropriate in a interview setting or would I expect to write code like the solution in the book.

The problem states

Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

Here is my code:

def transpose(the_array):
res = []
for i in range(len(the_array)):
transposed = []
for col in the_array:
transposed.append(col[i])
transposed.reverse()
res.append(transposed)
return res

print(transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))


Also, would the reverse method be ok to use in an interview?

I just realized my solution may not be considered in place.

• What does "1.7" refer to? – l0b0 Jan 15 at 0:55
• Your code does not work as pasted. Please fix the indentation. – l0b0 Jan 15 at 0:57

I just want to know if the code I wrote would be appropriate in a interview setting or would I expect to write code like the solution in the book.

As we cannot see the solution form the book, this is hard for us to answer.

Your solution seems to work which is ok for learning purposes, the biggest I can think of with your current code is List comprehension.

for col in the_array:
transposed.append(col[i])
transposed.reverse()


Could be

transposed = [col[i] for col in the_array][::-1]


Note how instead of .reverse() I use the slice annotation to reverse the list [::-1]

We could even make the first for loop another list comprehension (essentially creating a double list comprehension)

def transpose2(the_array):
return [
[col[i] for col in the_array][::-1]
for i in range(len(the_array))
]


I should note though that is is a rather elaborate way of writing

def transpose3(arr):
return zip(*arr[::-1])


Where the zip rotates the reversed list with argument unpacking