Magicsheet logo

Rotate Image

Medium
48.3%
Updated 6/1/2025

Rotate Image

What is this problem about?

The Rotate Image interview question asks you to rotate an n×n 2D matrix 90 degrees clockwise in-place. You cannot allocate another 2D matrix — the rotation must be performed directly on the input matrix. This is a foundational matrix manipulation problem with a clean mathematical solution using two operations: transpose and horizontal flip.

Why is this asked in interviews?

This problem is asked at J.P. Morgan, Apple, Cisco, Uber, Goldman Sachs, Microsoft, Meta, Amazon, Google, Bloomberg, Adobe, and virtually every major tech company because it appears in image processing (rotating photos), game development (rotating game boards), and computer graphics. The in-place constraint forces candidates to think mathematically rather than using a simple copy — separating those who understand matrix geometry from those who rely on extra space.

Algorithmic pattern used

The pattern is transpose then horizontal reverse (for 90° clockwise rotation). Transpose: swap matrix[i][j] with matrix[j][i] for all i < j. Horizontal reverse: reverse each row. For 90° counter-clockwise: transpose then vertical reverse (reverse each column). Both operations are O(n^2) time and O(1) space.

Alternatively, use the four-cell rotation: rotate four corresponding cells simultaneously, one layer at a time from outside in.

Example explanation

Matrix:

1 2 3
4 5 6
7 8 9

Step 1 — Transpose (swap across main diagonal):

1 4 7
2 5 8
3 6 9

Step 2 — Reverse each row:

7 4 1
8 5 2
9 6 3

Result: 90° clockwise rotation. Verify: original corner 1 (top-left) → bottom-left after 90° CW. ✓

Common mistakes candidates make

  • Transposing incorrectly — only swap (i,j) with (j,i) when i < j to avoid double-swapping.
  • Confusing clockwise (transpose + reverse rows) with counter-clockwise (transpose + reverse columns).
  • Using a copy of the matrix and then writing back — correct but not in-place.
  • The four-cell rotation: getting the indices wrong; derive them from the layer and offset systematically.

Interview preparation tip

For the Rotate Image coding problem, the array and matrix interview pattern via transpose-then-flip is the clean solution. Memorize: 90° CW = transpose + reverse each row; 90° CCW = transpose + reverse each column; 180° = reverse each row + reverse each column. Interviewers at Tesla and Nvidia often ask for all three rotation directions — knowing these three rules impresses. Practice on a 3×3 matrix to verify your transpose boundaries.

Similar Questions