Quick revision
The short answer
Rotating a square matrix is a matrix transformation problem. A clockwise quarter turn sends the value at (i, j) to (j, n - 1 - i), and we can do it in place with two passes of swaps: transpose the matrix across its diagonal, then reverse every row. It takes O(n squared) time, which is the best possible, and O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Brute force: copy into a new matrix | O(n^2) | O(n^2) |
| Four cells at a time, ring by ring | O(n^2) | O(1) |
| Transpose, then reverse each row | O(n^2) | O(1) |
What to remember
We turned a square matrix a quarter turn clockwise in place. The address rule says old (i, j) goes to (j, n - 1 - i); a transpose across the diagonal followed by a mirror of every row gives exactly that, and both passes are made only of swaps, so no number is lost. It takes O(n squared) time and O(1) space. The clue to remember is a square grid that must be turned or flipped: write the new address as a formula first, then build it from swaps.
1What it means to turn a matrix a quarter turn
Take a square tile of paper and write nine numbers on it in three rows: 1 2 3 on top, 4 5 6 in the middle, 7 8 9 at the bottom. Now turn the tile a quarter turn to the right on your desk, the way a clock hand moves. Look at it again. The top row, 1 2 3, now runs down the right edge, and the left column, 1 4 7, now runs along the top, read as 7 4 1. That is the whole problem: we must make the numbers in the computer look the way the turned tile looks.
A matrix is this tile in the computer, a grid of numbers stored as rows. In Java it is an int[][], an array of rows, where m[i][j] means the value in row i and column j. Both counts start at 0, so m[0][1] is the 2, top row, second column. Square means the number of rows equals the number of columns; we call that number n, and here n is 3.
Let us find the answer by hand. After the turn the first row is the old first column read from bottom to top, 7 4 1. The second row is the old middle column read bottom to top, 8 5 2, and the third is 9 6 3. So the rotated matrix is [7, 4, 1], [8, 5, 2], [9, 6, 3].
Follow one number to be sure. The 2 starts in row 0, column 1. On the turned tile it sits in the middle of the right edge, which is row 1, column 2. Keep this in mind, because the whole solution is about sending every number to its new address without losing any on the way.
Left: the matrix we are given. Right: the matrix after turning it 90 degrees clockwise.
1The old first column, read from the bottom, 7 4 1, becomes the new first row. The centre 5 stays where it is.
What to assume
- Clockwise or anticlockwise?
- We assume clockwise.
- Must we change the matrix itself, or may we return a new one?
- Interviewers usually ask for in place, meaning we change the given matrix and use only a few extra variables.
- Is it always square?
- Yes; a rectangle changes shape when turned, so it cannot be done in place. An empty or 1 by 1 matrix stays as it is.
The problem looks like a lot of bookkeeping, but it is gentler than it seems. There are only nine numbers, every one has exactly one new address, and we will find a rule that gives that address. After that, the only real question is how to move numbers so that none is overwritten too early.
A careful candidate asks a few questions first. Clockwise or anticlockwise? We assume clockwise, and the other way is in the questions at the end. Must we change the matrix itself, or may we return a new one? Interviewers usually ask for in place, meaning we change the given matrix and use only a few extra variables. Is it always square? Yes; a rectangle changes shape when turned, so it cannot be done in place. An empty or 1 by 1 matrix stays as it is.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a matrix transformation pattern
A beginner who reads this question for the first time often freezes, because it feels like geometry and nobody wants to do geometry in an interview. The usual first move is to stare at the grid and try to shuffle numbers around in one's head. That gets confusing quickly, because after a few moves you no longer remember which numbers have already moved. So instead of shuffling, let us read the question for clues.
The first clue is the word square. It tells us the shape does not change when we turn it, so the answer can live in the same n by n grid. That is what makes an in-place answer possible at all.
The second clue is the word rotate. A rotation moves every number, and moves it in a regular way, so there must be a rule that turns an old address into a new one. Let us find it from the example. The 2 went from row 0, column 1 to row 1, column 2. The 4 went from row 1, column 0 to row 0, column 1. The new row is always the old column, and the new column is n - 1 minus the old row. Written short, old (i, j) goes to new (j, n - 1 - i).
These clues point to the matrices and simulation family, and its pattern of matrix transformations. Simulation means we carry out the moves exactly as described instead of searching for a clever answer. The rule to carry to new problems is to write the new address of an element as a formula in i and j first, and only then decide how to move the elements. For turns and flips, the formula usually splits into two simple moves, a flip across the diagonal and a mirror of each row, which we will meet shortly.
Other grid problems look similar but are different at heart. Counting islands or finding paths in a maze searches from cell to neighbouring cell, and no number moves. Walking a matrix in spiral order goes around it ring by ring, which hints at another way to rotate, but it only reads values in a new order and moves nothing.
3The brute force, copying every number to a fresh matrix
With the address rule in hand, the honest first attempt is the brute force, and it is a good one. We make a second, empty n by n matrix and copy each old m[i][j] into out[j][n - 1 - i]. Because we never write into the matrix we are reading from, nothing can be overwritten too early. This is exactly what you would do with paper: copy the numbers onto a fresh tile in their new places.
Let us do the first row by hand, with n - 1 = 2. The 1 at (0, 0) goes to (0, 2). The 2 at (0, 1) goes to (1, 2). The 3 at (0, 2) goes to (2, 2). So the old top row fills the right edge of the new matrix, exactly as the turned tile showed. The other two rows fill the middle and left columns the same way.
Now let us count. There are 9 numbers, and each is read once and written once, so 9 copies. For n by n that is n squared copies, written O(n squared), read as order n squared. We cannot do better than that, because every number except the centre has to move.
The cost is the second matrix, another n squared cells of memory, so the extra space is O(n squared). For a photograph of 10,000 by 10,000 pixels stored as ints, that is about 400 megabytes, only to hold a copy for a moment.
So where is the waste? Not in the time, but in the memory. The second matrix exists only because writing straight into the first one would destroy numbers we have not moved yet. If we could find moves that never destroy a number before it reaches its new home, we would not need the copy.
4Getting to the in-place turn, one observation at a time
A beginner naturally asks why we cannot use the same rule and write into the same matrix. Let us try it and see what we lose. The first write sends the 1 at (0, 0) to (0, 2). But (0, 2) was holding the 3, and the 3 has not moved yet. It is gone. We ran this version on the example, and the picture shows the result.
Writing old[i][j] straight into the same matrix at [j][n - 1 - i] overwrites values before they have been moved.
- write
- m[0][2] = m[0][0]
- lost
- 3
1The first write puts 1, from row 0 column 0, into its new home at row 0 column 2. The 3 that lived there is gone before we ever moved it.
- wanted
- 7 4 1, 8 5 2, 9 6 3
- got
- 7 4 1, 2 5 2, 1 2 1
2After all nine writes the matrix reads 7 4 1, 2 5 2, 1 2 1. The 3, 6, 8 and 9 were overwritten, and later writes copied the damaged values.
So we need moves that never destroy a number. The safest move of all is a swap, where two numbers trade places. In Java a swap uses one temporary variable, the way swapping the drinks in two glasses needs a third glass. Nothing is lost, because each number is held somewhere at every moment. Can the turn be built entirely out of swaps? Let us go back to the paper tile.
Take the tile and flip it over along the line from its top left corner to its bottom right corner. That line is called the main diagonal, and it holds 1, 5 and 9. The flip is called a transpose: every number at (i, j) moves to (j, i), so rows become columns. The 2 at (0, 1) and the 4 at (1, 0) trade places, and the numbers on the diagonal stay put. A transpose is made of swaps of pairs across the diagonal.
Now mirror each row, left to right. A number at column c moves to column n - 1 - c in the same row, and that too is just swaps, the outer pair first and then inwards. Follow an element through both moves. The transpose sends (i, j) to (j, i), and the mirror sends (j, i) to (j, n - 1 - i). That is exactly the rotation rule from before, so the two flips together are a quarter turn. Check it on the 2: (0, 1) becomes (1, 0), which becomes (1, 2), its right home.
There is one trap in the transpose, and almost everyone falls into it once. It is tempting to loop j over the whole row. But then the pair (0, 1) is swapped once when i = 0 and swapped back when i = 1. Every pair is swapped twice and the matrix ends exactly as it started, which we confirmed by running it. So j must start at i + 1, which means we only touch pairs above the diagonal, each exactly once.
There is also a middle path some people find first. We can move four numbers at a time around the square, one ring at a time from the outside in, saving one number in a temporary. It is also in place, but its four index expressions are easy to get wrong under pressure, while the two flips are two short loops anyone can check.
5Watching the two flips on the example
The picture plays the method on our matrix. The first three frames after the start are the transpose, one swap each. The next three mirror the three rows. The cells being swapped are marked as looked at, and finished rows are marked as done.
While you watch, keep an eye on two things. During the transpose, the diagonal 1, 5, 9 never moves. And after the transpose, each row already holds the right numbers, only in the wrong order.
Cells being swapped are marked as looked at; finished rows are marked as done.
- step
- start
- n
- 3
1We start from the example. The diagonal, 1, 5 and 9, runs from the top left corner to the bottom right, and the transpose will leave it alone.
- step
- transpose
- i, j
- 0, 1
- swapped
- 2 and 4
2Transpose, i = 0 and j = 1. We swap m[0][1] with m[1][0], so 2 and 4 trade places across the diagonal.
- step
- transpose
- i, j
- 0, 2
- swapped
- 3 and 7
3Still on row i = 0, j = 2. We swap m[0][2] with m[2][0], so 3 and 7 trade places. Row 0 now holds the old first column, 1 4 7.
- step
- transpose
- i, j
- 1, 2
- swapped
- 6 and 8
4Row i = 1, j = 2. We swap m[1][2] with m[2][1], so 6 and 8 trade places. The transpose is finished: every row holds an old column.
- step
- reverse rows
- row
- 0
5Now we reverse each row with two pointers. Row 0 swaps its ends, 1 and 7, and the middle 4 stays, giving 7 4 1, the first row of the answer.
- step
- reverse rows
- row
- 1
6Row 1 swaps its ends, 2 and 8, giving 8 5 2. The centre value 5 has not moved at all, which is true of the centre of any odd-sized square.
- step
- reverse rows
- row
- 2
7Row 2 swaps its ends, 3 and 9, giving 9 6 3. Every row is now reversed, and the loop over the rows ends.
- result
- [[7,4,1],[8,5,2],[9,6,3]]
- swaps
- 3 + 3
8The matrix reads 7 4 1, 8 5 2, 9 6 3, the same as the copy, using only nine cells and one temporary variable for every swap.
Read the fourth frame carefully. After three swaps the rows are 1 4 7, 2 5 8 and 3 6 9, which are the old columns. The answer needs 7 4 1, 8 5 2 and 9 6 3, the same numbers in each row, back to front. That is why mirroring each row finishes the job.
In each mirror frame only the two ends of a row trade places, because a row of three has only one outer pair; the middle number stays. On a 4 by 4 matrix each row would make two swaps, the outer pair and then the inner pair.
6The complete Java program
Here is the full class. It holds the in-place rotation and the copying version, which doubles as a check. main rotates the example both ways, rotates a 4 by 4 matrix and prints its new first row, and rotates a 1 by 1 matrix. Each comment shows what that line prints.
Let us read rotateClockwise in the order it runs. n is the side of the square. The first pair of loops is the transpose. i walks down the rows, and j starts at i + 1, so we only visit cells to the right of the diagonal. For each such cell, the three lines with tmp swap m[i][j] with its mirror m[j][i]: we save one value in tmp, copy the other over it, and put the saved value in the other place.
The second loop mirrors each row. For each row it sets l at the left end and r at the right end, swaps the two values, and moves both pointers one step inwards. The test l < r stops it when they meet in the middle, so the centre of an odd row is never touched and no pair is swapped twice.
rotatedCopy is the brute force kept for checking. main first prints the copy of the example, then rotates the example in place and prints it again, and both lines read [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. The 4 by 4 matrix has no centre, and its new first row, [13, 9, 5, 1], is its old first column read from the bottom. The 1 by 1 matrix comes back as [[42]].
7How much it costs, and the cases at the edges
Let us count on the example first. The transpose made 3 swaps, one for each pair above the diagonal, and the mirror made 3 more, one per row, 6 swaps in all. For n by n the transpose makes n(n - 1) / 2 swaps and the mirror makes about n / 2 per row, n squared / 2 in all, so the time is O(n squared), the same as the copy and the best possible, since every number must move.
The space is where we win. We used one temporary variable and a few indexes, however large the matrix, so the extra space is O(1), read as constant, against O(n squared) for the copy.
| Approach | Time | Extra space |
|---|---|---|
| Brute force: copy into a new matrix | O(n^2) | O(n^2) |
| Four cells at a time, ring by ring | O(n^2) | O(1) |
| Transpose, then reverse each row | O(n^2) | O(1) |
The edge cases need no special code. For a 0 by 0 or 1 by 1 matrix both loops do nothing, and the matrix is already its own rotation. Odd and even sizes use the same loops; an odd size simply leaves the centre untouched. A rectangle of r rows and c columns turns into c rows and r columns, so it needs a new matrix, with the rule out[j][r - 1 - i] = m[i][j].
8Follow-up questions
How do you rotate anticlockwise instead?
Use the same two flips in the other combination. Transpose, and then mirror each column instead of each row, which means swapping the top and bottom rows. Check it with the address rule: an anticlockwise turn sends (i, j) to (n - 1 - j, i), and the 3 in the top right corner moves to the top left, as turning the paper tile to the left shows.
How does the ring-by-ring rotation work?
We treat the matrix as rings, from the outside in. For each position along the top edge of a ring, we save the top value in a temporary, move the left value up, the bottom value to the left, the right value down, and the saved value to the right. Each number moves once, so it is O(n squared) time and O(1) space, with slightly fewer writes, but four index expressions must all be right.
How would you rotate by 180 degrees?
A half turn is two quarter turns, so we can call the method twice. More directly, reversing the order of the rows and then mirroring each row gives the same result, because a half turn sends (i, j) to (n - 1 - i, n - 1 - j). Both are O(n squared) time and O(1) space.
9Conclusion
We turned a square matrix a quarter turn clockwise in place. The address rule says old (i, j) goes to (j, n - 1 - i); a transpose across the diagonal followed by a mirror of every row gives exactly that, and both passes are made only of swaps, so no number is lost. It takes O(n squared) time and O(1) space. The clue to remember is a square grid that must be turned or flipped: write the new address as a formula first, then build it from swaps.
Open with
Let me confirm the setup: the matrix is square, I rotate clockwise, and I should change it in place. A first approach copies each m[i][j] into a new matrix at [j][n - 1 - i].
Then, if they want more
That is O(n squared) time, which is optimal because every element moves, but O(n squared) extra space. Writing into the same matrix with that rule fails, because it overwrites values that have not moved yet. So I split the rotation into two moves made only of swaps.
First I transpose: for each i, and j from i + 1, I swap m[i][j] with m[j][i]. Starting j at i + 1 matters, because swapping every pair twice would undo the transpose. Then I reverse each row with two pointers.
The transpose sends (i, j) to (j, i), the reversal sends that to (j, n - 1 - i), which is the rotation. On the 3 by 3 example that is three swaps for the transpose and three for the rows.
It is O(n squared) time and O(1) extra space, and a 1 by 1 or empty matrix needs no special case.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 22 times in that collection. How it is counted
- Official documentation
- Arrays (Java 21), java.util, package documentation
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 "Rotate a square matrix by 90 degrees.": https://scrivio-interview-library.netlify.app/data-structures/solutions/rotate-a-square-matrix-by-90-degrees-7fef06/