150NeetCode 150

136.Rotate Image

MediumBlind 75Math & Geometry Ā· 1/8

Problem

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise.

The rotation must be done in place — modify matrix directly; do not allocate another 2D matrix to hold the result.

Examples

Input:  matrix = [[1,2,3],
                  [4,5,6],
                  [7,8,9]]
Output:          [[7,4,1],
                  [8,5,2],
                  [9,6,3]]
Input:  matrix = [[5,1,9,11],
                  [2,4,8,10],
                  [13,3,6,7],
                  [15,14,12,16]]
Output:          [[15,13,2,5],
                  [14,3,4,1],
                  [12,6,8,9],
                  [16,7,10,11]]

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

šŸ’” Key Insight

A clockwise rotation sends cell (r, c) to (c, n - 1 - r). That mapping is a transpose ((r, c) → (c, r)) followed by a horizontal flip of each row ((c, r) → (c, n - 1 - r)) — two simple in-place passes. Alternatively, cells move in cycles of four around each square ring, and you can rotate each cycle with a single temporary variable.

Extra Matrix (Brute Force)

TimeO(n²)SpaceO(n²)

Intuition

Write each element straight to its rotated position in a copy, then copy back. The rule: element at row r, column c ends up at row c, column n - 1 - r (the first row becomes the last column).

Algorithm

  1. Create rotated[n][n].
  2. For every (r, c): rotated[c][n - 1 - r] = matrix[r][c].
  3. Copy rotated back into matrix row by row.

Visualization

matrix          rotated
1 2 3           7 4 1
4 5 6    -->    8 5 2
7 8 9           9 6 3

row 0 (1,2,3) becomes column 2 read top-down
row 2 (7,8,9) becomes column 0 read top-down

Code

java
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] rotated = new int[n][n];
        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                rotated[c][n - 1 - r] = matrix[r][c]; // row r becomes column n-1-r
            }
        }
        for (int r = 0; r < n; r++) {
            System.arraycopy(rotated[r], 0, matrix[r], 0, n);
        }
    }
}

Complexity

  • Time: O(n²) — every cell is written twice.
  • Space: O(n²) — the extra matrix (violates the in-place requirement).

Complexity Comparison

Approach Time Space
Extra Matrix O(n²) O(n²)
Four-way Cycle O(n²) O(1)
Transpose + Reverse O(n²) O(1)

Common Pitfalls

  • Transposing over the full matrix (c from 0) — each pair is swapped twice and the matrix ends up unchanged.
  • Reversing columns instead of rows after the transpose — that rotates counter-clockwise.
  • Assigning matrix = rotated in Approach 1 — that only rebinds the local reference; the caller's matrix is untouched.
  • In the ring method, looping i up to last inclusive — the corner would be rotated twice.