Rotate Image

MediumMatrix · In-Place Transform🧩 Matrix TraversalLeetCode #48 ↗Updated

Problem

You are given an n × n grid of integers representing an image. Turn the image 90° clockwise, changing the grid in-place — you may not build and return a second matrix.
Input[[1,2,3],[4,5,6],[7,8,9]]Output[[7,4,1],[8,5,2],[9,6,3]]
Input[[1,2],[3,4]]Output[[3,1],[4,2]]

n == matrix.length == matrix[i].length  ·  1 ≤ n ≤ 20  ·  -1000 ≤ matrix[i][j] ≤ 1000  ·  In-place only.

Try it yourself

Java
class Solution {
    public void rotate(int[][] matrix) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A clockwise turn sends cell (i, j) to (j, n-1-i). That mapping equals a transpose ((i,j)→(j,i)) followed by a horizontal mirror ((j,i)→(j,n-1-i)) — both trivially in-place.
PatternMatrix Traversal

Instinct A 2D grid you must walk in a fixed geometric order (spiral, diagonal, layer, rotate) or update in place - think boundaries, direction vectors and index maths.

Memory hack Walk the walls, then shrink the room - four fences (top, bottom, left, right) close in after every lap.

Open the Matrix Traversal guide →

Approaches

Brute ForceAuxiliary Matrix

Time O(n2)Space O(n2)

Apply the rotation formula directly: write matrix[i][j] into rotated[j][n-1-i] of a fresh grid, then copy the grid back. A second buffer means no value is overwritten before it is read.

Java
public void rotate(int[][] matrix) {
    int n = matrix.length;
    int[][] rotated = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            rotated[j][n - 1 - i] = matrix[i][j];
        }
    }
    for (int i = 0; i < n; i++) {
        System.arraycopy(rotated[i], 0, matrix[i], 0, n);
    }
}

Direct and bug-free, but the O(n2) buffer violates the in-place rule.

At a glance

LevelApproachTimeSpace
Brute ForceAuxiliary MatrixO(n2)O(n2)
BetterTranspose, then Reverse RowsO(n2)O(1)
OptimalLayer-by-Layer 4-Way CycleO(n2)O(1)
Common pitfalls
  • Transposing with j from 0 — each pair swaps twice and nothing changes.
  • Reversing columns instead of rows — that rotates counter-clockwise.
  • Off-by-one on ring bounds: inner loop runs first..last-1, not to last.
Interview tips
  • Derive (i,j)→(j,n-1-i) first; every approach falls out of it.
  • Mention the counter-clockwise variant: transpose, then reverse each column.
  • Offer the ring version when asked to minimise writes or do it in one pass.
Pattern
Compose simple in-place transforms → rotations/flips of a matrix without extra memory.
My notes saved in this browser