DEV Community

Discussion on: Interview Prep #6: Rotate Image

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

This is an interesting (and practical) problem.

I have trouble following the solution, though.

Here's the pattern I noticed:

1) Row #1 becomes Column #3
2) Row #2 becomes Column #2
3) Row #3 becomes Column #1

Basically, if the matrix is nxn, Row #i becomes Column #n-i+1.

But we can make things easier for ourselves by switching up our perspective:

1 2 3
4 5 6
7 8 9

Algorithm:

For col = 0 through n - 1:

Iterate through the rows in reverse: row = n - 1 through 0 and fill the new matrix with original[row][col]

7 4 1
8 5 2
9 6 3
Collapse
 
godcrampy profile image
Sahil Bondre

Yea, your solution will work as well. It's just that it will take additional O(n2) space as we are creating a new matrix. The pattern that you mentioned is indeed what the algorithm mentioned by me does. But, since it tries to do in-place, we rotate one number of row/column at a time.