Rotate an n × n matrix by 90 degrees clockwise in place.

Rotating a square matrix 90 degrees clockwise in place takes two steps: transpose it (swap matrix[i][j] with matrix[j][i]), then reverse each row.

Key Points

import java.util.Arrays;

public class RotateMatrix {

    static void rotateClockwise(int[][] m) {
        int n = m.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t;
            }
        }
        for (int[] row : m) {
            for (int l = 0, r = n - 1; l < r; l++, r--) {
                int t = row[l]; row[l] = row[r]; row[r] = t;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        rotateClockwise(matrix);
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Output

[7, 4, 1]

[8, 5, 2]

[9, 6, 3]

Good to Know

Another in-place method rotates the matrix layer by layer, moving four elements at a time in a cycle. It does the same work but is easier to get wrong under pressure.

Draw the 3 × 3 example after the transpose step; seeing [1,4,7] become [7,4,1] makes the second step obvious.

Interview Tip

A concise interview answer is

I rotate in place by first transposing the matrix, swapping matrix[i][j] with matrix[j][i], and then reversing every row. That is O(n²) time with O(1) extra space, and for counter-clockwise I would reverse the columns instead of the rows.

Last updated: 11 November 2026

Previous question: Merge two sorted linked lists into one sorted linked list.

Next question: Add the digits of a number repeatedly until a single digit remains.

More Java Coding Questions interview questions

All Java Coding Questions questions