↻one more pass.
Matrices · Medium

Rotate Image: the idea to remember.

Rotate a square matrix ninety degrees clockwise in place.

Solve on LeetCode ↗

The core insight

Swap cells across the main diagonal, then reverse every row.

Why it works

Transposing maps (r,c) to (c,r); reversing rows maps that to (c,n minus one minus r), the clockwise rotated position.

The mistake to avoid

Only swap one triangle during transpose. Applying both triangles undoes the transformation.

Time: O(n²)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

void rotate(int[][] a) {
    int n = a.length;
    for (int r = 0; r < n; r++) for (int c = r + 1; c < n; c++) {
        int temp = a[r][c]; a[r][c] = a[c][r]; a[c][r] = temp;
    }
    for (int[] row : a) for (int l = 0, r = n - 1; l < r; l++, r--) {
        int temp = row[l]; row[l] = row[r]; row[r] = temp;
    }
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.