Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Java method that rotates an n x n int matrix 90 degrees clockwise in place. Explain the steps and the complexity, and say what changes for a non-square matrix.

We rotate an n x n matrix 90 degrees clockwise in two in-place steps: first transpose it by swapping m[i][j] with m[j][i] for every j > i, then reverse each row. An alternative rotates four cells at a time, layer by layer from the outside in. Both are O(n^2) time, which is optimal because every cell moves, and O(1) extra space. A non-square m x n matrix cannot be rotated in place in Java's array-of-arrays layout, because the result has a different shape, so we allocate a new n x m array and set result[j][m - 1 - i] = a[i][j].

Why this question is asked

Rotating a matrix shows up in image processing, in games that rotate a board or a piece, and in any code that changes the orientation of grid data. Interviewers like it because the index arithmetic is easy to get wrong, and because there is an elegant decomposition into two simpler operations that is much easier to write correctly under pressure. In this answer, we will recap where each cell has to go, build the transpose-and-reverse solution and see why it works, look at the four-way swap alternative, discuss complexity, and then handle non-square matrices and counterclockwise rotation.

1A Quick Recap of Where Each Cell Goes

Rotating clockwise by 90 degrees turns the first row into the last column, the second row into the second-to-last column, and so on. In index terms, the cell at row i, column j moves to row j, column n - 1 - i. For the 3 x 3 matrix with rows [1, 2, 3], [4, 5, 6], [7, 8, 9], the result has rows [7, 4, 1], [8, 5, 2], [9, 6, 3]: the old first column, read from the bottom up, becomes the new first row.

In place means we change the given int[][] without allocating a second matrix. The difficulty is that writing a cell to its new position overwrites a value we still need, so we must move values in a careful order.

2Transpose, Then Reverse Each Row

The transpose of a matrix flips it across its main diagonal, the line from top left to bottom right: the cell at (i, j) swaps with the cell at (j, i). Reversing a row then mirrors the matrix left to right. Together, these two mirror images produce a rotation.

Java
static void rotateClockwise(int[][] m) {
int n = m.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // only above the diagonal: each pair once
int t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t;
}
}
// after transpose: [1,4,7] [2,5,8] [3,6,9]
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;
}
}
// after reversing rows: [7,4,1] [8,5,2] [9,6,3]
}
A 3 x 3 matrix through both steps
RowOriginalAfter transposeAfter reversing rows
01 2 31 4 77 4 1
14 5 62 5 88 5 2
27 8 93 6 99 6 3
Two simple mirror operations combine into one rotation.

Why does this work? The transpose moves (i, j) to (j, i). Reversing the row moves column i to column n - 1 - i, so the cell ends at (j, n - 1 - i), which is exactly where a clockwise rotation must put it.

Notice that the transpose loop starts at j = i + 1. If it ran over every j, each pair would be swapped twice, once from each side, and the matrix would end up unchanged. Diagonal cells stay where they are, so we skip j = i as well.

3The Four-Way Swap, Layer by Layer

The other classic approach thinks of the matrix as rings, called layers, from the outside in. In each layer, four cells form a cycle under rotation: top goes to right, right to bottom, bottom to left, and left to top. We save one of them and shift the other three.

Java
static void rotateLayers(int[][] m) {
int n = m.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer, last = n - 1 - layer;
for (int i = first; i < last; i++) {
int offset = i - first;
int top = m[first][i]; // save top
m[first][i] = m[last - offset][first]; // left -> top
m[last - offset][first] = m[last][last - offset]; // bottom -> left
m[last][last - offset] = m[i][last]; // right -> bottom
m[i][last] = top; // top -> right
}
}
}

Each cell is read and written exactly once, so this version does a bit less work than transposing and reversing, which touches each cell twice. But the index expressions are easy to get wrong, and a mistake usually shows up only on 4 x 4 or larger matrices. In an interview, I would write the transpose version and describe this one.

4Complexity

Both versions touch each of the n^2 cells a constant number of times, so they are O(n^2) time. We cannot do better, because almost every cell has to move. They use only a few loop variables and one temporary, so the extra space is O(1). For a 4,000 x 4,000 matrix of ints, that is 16 million cells, 64 MB we do not need to allocate a second time.

5What Changes for a Non-Square Matrix

A matrix with m rows and n columns becomes, after rotation, a matrix with n rows and m columns. In Java, an int[][] is an array of row arrays, each with a fixed length. A 2 x 3 matrix is two arrays of length 3, and its rotation needs three arrays of length 2. We cannot reshape arrays in place, so we allocate a new one and fill it with the general formula.

Java
static int[][] rotateClockwise(int[][] a) {
int m = a.length, n = a[0].length; // m rows, n columns
int[][] result = new int[n][m]; // n rows, m columns
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[j][m - 1 - i] = a[i][j];
}
}
return result;
}
// [[1, 2, 3],
// [4, 5, 6]] -> [[4, 1],
// [5, 2],
// [6, 3]]

This version is O(m n) time and O(m n) extra space for the result. If the data were stored in a single flat array, an in-place rotation of a non-square matrix is possible in theory by following permutation cycles, but it is complicated and slow in practice, so the new array is the sensible answer.

6Follow-up questions

How would you rotate counterclockwise?

I transpose and then reverse each column instead of each row, which is the same as reversing the order of the rows. Another way is to reverse each row first and then transpose. For the 3 x 3 example the result has rows [3, 6, 9], [2, 5, 8], [1, 4, 7]. Rotating counterclockwise by 90 degrees is also the same as rotating clockwise three times, but that does three times the work.

How would you rotate by 180 degrees?

A 180 degree rotation sends (i, j) to (n - 1 - i, n - 1 - j), so I reverse the order of the rows and then reverse each row. It is also O(n^2) time and O(1) space.

Why is the transpose loop limited to j > i?

Because a transpose swaps pairs, and each pair (i, j) and (j, i) must be swapped exactly once. Looping over all j would swap every pair twice and leave the matrix as it was, and the diagonal cells do not move at all.

7Conclusion

In this answer, we saw that a clockwise rotation moves cell (i, j) to (j, n - 1 - i), and that two in-place steps produce it: a transpose, swapping only above the diagonal, then reversing each row. The four-way swap rotates layer by layer and touches each cell once, at the cost of trickier indexes. Both are O(n^2) time and O(1) space. A non-square matrix needs a new n x m array filled with result[j][m - 1 - i] = a[i][j], and a counterclockwise rotation is a transpose followed by reversing the columns.

What to say in the interviewAbout 100 seconds aloud

Open with

I would do it in two in-place steps. First I transpose the matrix, swapping each cell above the diagonal with its mirror below, so m i j swaps with m j i, only for j greater than i, otherwise every pair would be swapped twice and nothing would change.

Then, if they want more

Then I reverse each row with two pointers. The transpose sends row i column j to row j column i, and reversing the row sends column i to column n minus one minus i, which is exactly where a clockwise rotation needs the cell.

For 1 2 3, 4 5 6, 7 8 9, the transpose gives 1 4 7, 2 5 8, 3 6 9, and reversing each row gives 7 4 1, 8 5 2, 9 6 3.

The alternative is to go layer by layer from the outside and rotate four cells at a time, saving the top and shifting left to top, bottom to left and right to bottom. It touches each cell once, but the indexes are easier to get wrong, so I would describe it and code the transpose version.

Both are O(n squared), which is optimal since every cell moves, and O(1) extra space.

For a non-square matrix, the shape changes from m by n to n by m, and in Java an int array of arrays cannot change its row lengths, so I would allocate a new n by m array and set result j, m minus one minus i, to a i j.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a Java method that rotates an n x n int matrix 90 degrees clockwise in place....": https://scrivio-interview-library.netlify.app/java/coding-problems/9465f5e052/