Rotate Image
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Rotate an n x n matrix 90 degrees clockwise, in place.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Where does the cell at row 0, column 2 end up after a clockwise turn?
- Hint 2Try swapping matrix[row][column] with matrix[column][row] first.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Turning a photo a quarter turn to the right in two easy moves. First flip it along the diagonal from the top-left to the bottom-right corner (what was a row becomes a column). Then mirror each row left-to-right. Together they are exactly a quarter turn clockwise.
- The obvious way
Build a new matrix and copy each cell to its rotated place: O(n²) extra space.
- The key insight
Transpose: for each pair with column > row, swap matrix[row][column] and matrix[column][row]. Then reverse every row. Both steps are in place.
- The algorithm
- Swap each cell above the diagonal with its mirror below.
- Now rows and columns are exchanged (transposed).
- Reverse every row.
- The matrix is rotated.
Watch it run
Examplematrix = [[1,2,3],[4,5,6],[7,8,9]]
Flip along the diagonal: rows become columns. The matrix is now [[1,4,7],[2,5,8],[3,6,9]].
[[1,4,7],[2,5,8],[3,6,9]]
Where people slip
- Transpose only pairs with column > row; swapping all pairs would undo itself.
- For a counter-clockwise turn, reverse the rows first (or transpose along the other diagonal).
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def rotate(matrix):
size = len(matrix)
for row in range(size):
for column in range(row + 1, size):
matrix[row][column], matrix[column][row] = matrix[column][row], matrix[row][column] # flip along the diagonal
for row in matrix:
row.reverse() # mirror each rowNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.