AlgoMaster Logo

Rotate Image

mediumFrequency11 min readUpdated June 23, 2026

Understanding the Problem

We need to rotate an n x n matrix 90 degrees clockwise, and we must do it in-place. The first step is to figure out where each element moves.

Track where one row goes. The first row [1, 2, 3] becomes the last column, read top to bottom. The last row [7, 8, 9] becomes the first column. Generalizing this, the element at position (i, j) moves to position (j, n - 1 - i). The row index i becomes the new column index, and the old column index j becomes the new row index, counted from the bottom. This single formula is the foundation for every approach below.

Key Constraints:

  • n == matrix.length == matrix[i].length means the matrix is always square. Rotating a rectangular matrix would swap its dimensions, but a square matrix keeps the same shape, which is what makes an in-place rotation possible.
  • 1 <= n <= 20 keeps the matrix small (at most 400 elements), so time is not the constraint. The real requirement is in the problem statement: rotate in-place, without allocating a second matrix.
  • -1000 <= matrix[i][j] <= 1000 means values fit in a 32-bit integer with no overflow concerns. Every approach only moves values around, never adds them, so the value range never matters beyond storage.

Approach 1: Using Extra Space

Intuition

Apply the rotation formula directly. Element (i, j) moves to (j, n - 1 - i), so we can allocate a second matrix, write every element into its rotated position, then copy the result back into the original.

This violates the in-place constraint, but it isolates the index mapping from the harder problem of doing the same moves without a scratch buffer. Once the formula is correct here, the later approaches reuse it.

Algorithm

  1. Create a new n x n matrix rotated.
  2. For each element at position (i, j) in the original matrix, place it at (j, n - 1 - i) in rotated.
  3. Copy all values from rotated back into the original matrix.

Example Walkthrough

Take matrix = [[1,2,3],[4,5,6],[7,8,9]], so n = 3. The first loop writes each element into rotated[j][n-1-i]:

After the first loop, rotated = [[7,4,1],[8,5,2],[9,6,3]]. The second loop copies every value of rotated back into matrix, leaving matrix = [[7,4,1],[8,5,2],[9,6,3]], which is the input rotated 90 degrees clockwise.

Code

This allocates an entire n x n matrix to hold intermediate results, which the problem forbids, and it writes every element twice. The next approach decomposes the rotation into two passes that each rearrange the matrix in-place, removing the extra storage.

Approach 2: Transpose + Reverse

Intuition

A 90-degree clockwise rotation equals transposing the matrix and then reversing each row. The two operations compose into the rotation formula.

Transposing swaps rows and columns, sending element (i, j) to (j, i). Reversing each row then sends (j, i) to (j, n - 1 - i). Composing the two gives (i, j) -> (j, n - 1 - i), the rotation formula from the start of the chapter. Both transposing and reversing each row are in-place operations built from swaps, so no second matrix is required.

Algorithm

  1. Transpose the matrix: For each pair (i, j) where i < j, swap matrix[i][j] with matrix[j][i]. The i < j bound visits each off-diagonal pair once; visiting every pair would swap each one twice and undo the transpose.
  2. Reverse each row: For each row, swap elements from the outside in (left and right pointers moving toward the center).

Example Walkthrough

Take matrix = [[1,2,3],[4,5,6],[7,8,9]], so n = 3.

Step 1, transpose. The inner loop runs only for j > i, swapping across the main diagonal:

The diagonal entries 1, 5, 9 stay put, and the matrix is now [[1,4,7],[2,5,8],[3,6,9]].

Step 2, reverse each row:

The result is [[7,4,1],[8,5,2],[9,6,3]], the same answer as Approach 1, produced with only a single temporary variable.

Code

This approach touches every element twice, once during transpose and once during row reversal. The next approach moves each element straight to its final position by rotating four elements at a time, so each element is written only once.

Approach 3: Four-Way Swap (Layer by Layer)

Intuition

Instead of decomposing the rotation into transpose plus reverse, move elements directly. Every element belongs to a cycle of four: the rotation sends element A to B's position, B to C's, C to D's, and D back to A's. The four positions in each cycle are the same distance from the center, one on each side of the matrix.

The matrix is a set of concentric square layers. The outermost layer is the border, the next layer is one ring inward, and so on. For each layer, walk along the top edge and perform one four-way swap per position.

For a position (top, left + i) on the top edge of a layer:

  • Top moves to Right: (top, left + i) to (top + i, right)
  • Right moves to Bottom: (top + i, right) to (bottom, right - i)
  • Bottom moves to Left: (bottom, right - i) to (bottom - i, left)
  • Left moves to Top: (bottom - i, left) to (top, left + i)

Saving one value in a temporary variable lets us move the other three without losing data, so all four elements reach their correct positions in a single pass over the layer.

Algorithm

  1. Process the matrix layer by layer, from the outermost layer inward. Each layer is defined by its top, bottom, left, and right boundaries.
  2. For each layer, iterate through positions along the top edge (excluding the last element, since it belongs to the next side).
  3. At each position, perform a four-way swap:
    • Save the top element.
    • Move the left element to the top.
    • Move the bottom element to the left.
    • Move the right element to the bottom.
    • Place the saved top element at the right.
  4. After processing all positions in the layer, shrink the boundaries inward and repeat.

Example Walkthrough

Take matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], so n = 4. With two layers, this shows both the boundary shrink and the four-way swap.

Layer 0 has top = 0, bottom = 3, left = 0, right = 3. The loop runs for i = 0, 1, 2:

The entire outer ring is now in place: [[13,9,5,1],[8,..,..,2],[15,..,..,3],[16,12,8,4]], with the four corners and edges rotated. Then top becomes 1 and bottom becomes 2.

Layer 1 has top = 1, bottom = 2, left = 1, right = 2. The loop runs once, for i = 0:

Now top becomes 2 and bottom becomes 1, so top < bottom is false and the loop ends. The final matrix is [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]], the input rotated 90 degrees clockwise. Every element was written exactly once.

Code