We need to rotate an n x n matrix 90 degrees clockwise, and we must do it in-place. The first step is to figure out where each element moves.
Track where one row goes. The first row [1, 2, 3] becomes the last column, read top to bottom. The last row [7, 8, 9] becomes the first column. Generalizing this, the element at position (i, j) moves to position (j, n - 1 - i). The row index i becomes the new column index, and the old column index j becomes the new row index, counted from the bottom. This single formula is the foundation for every approach below.
n == matrix.length == matrix[i].length means the matrix is always square. Rotating a rectangular matrix would swap its dimensions, but a square matrix keeps the same shape, which is what makes an in-place rotation possible.1 <= n <= 20 keeps the matrix small (at most 400 elements), so time is not the constraint. The real requirement is in the problem statement: rotate in-place, without allocating a second matrix.-1000 <= matrix[i][j] <= 1000 means values fit in a 32-bit integer with no overflow concerns. Every approach only moves values around, never adds them, so the value range never matters beyond storage.Apply the rotation formula directly. Element (i, j) moves to (j, n - 1 - i), so we can allocate a second matrix, write every element into its rotated position, then copy the result back into the original.
This violates the in-place constraint, but it isolates the index mapping from the harder problem of doing the same moves without a scratch buffer. Once the formula is correct here, the later approaches reuse it.
rotated.(i, j) in the original matrix, place it at (j, n - 1 - i) in rotated.rotated back into the original matrix.Take matrix = [[1,2,3],[4,5,6],[7,8,9]], so n = 3. The first loop writes each element into rotated[j][n-1-i]:
After the first loop, rotated = [[7,4,1],[8,5,2],[9,6,3]]. The second loop copies every value of rotated back into matrix, leaving matrix = [[7,4,1],[8,5,2],[9,6,3]], which is the input rotated 90 degrees clockwise.
This allocates an entire n x n matrix to hold intermediate results, which the problem forbids, and it writes every element twice. The next approach decomposes the rotation into two passes that each rearrange the matrix in-place, removing the extra storage.
A 90-degree clockwise rotation equals transposing the matrix and then reversing each row. The two operations compose into the rotation formula.
Transposing swaps rows and columns, sending element (i, j) to (j, i). Reversing each row then sends (j, i) to (j, n - 1 - i). Composing the two gives (i, j) -> (j, n - 1 - i), the rotation formula from the start of the chapter. Both transposing and reversing each row are in-place operations built from swaps, so no second matrix is required.
The same decomposition produces rotations in other directions, which is a useful check that the reasoning is about index transforms rather than a memorized recipe. For a 90-degree counter-clockwise rotation, reverse each row first and then transpose. For a 180-degree rotation, reverse every row and every column. Each direction is a different composition of transpose and reflect.
(i, j) where i < j, swap matrix[i][j] with matrix[j][i]. The i < j bound visits each off-diagonal pair once; visiting every pair would swap each one twice and undo the transpose.Take matrix = [[1,2,3],[4,5,6],[7,8,9]], so n = 3.
Step 1, transpose. The inner loop runs only for j > i, swapping across the main diagonal:
The diagonal entries 1, 5, 9 stay put, and the matrix is now [[1,4,7],[2,5,8],[3,6,9]].
Step 2, reverse each row:
The result is [[7,4,1],[8,5,2],[9,6,3]], the same answer as Approach 1, produced with only a single temporary variable.
This approach touches every element twice, once during transpose and once during row reversal. The next approach moves each element straight to its final position by rotating four elements at a time, so each element is written only once.
Instead of decomposing the rotation into transpose plus reverse, move elements directly. Every element belongs to a cycle of four: the rotation sends element A to B's position, B to C's, C to D's, and D back to A's. The four positions in each cycle are the same distance from the center, one on each side of the matrix.
The matrix is a set of concentric square layers. The outermost layer is the border, the next layer is one ring inward, and so on. For each layer, walk along the top edge and perform one four-way swap per position.
For a position (top, left + i) on the top edge of a layer:
(top, left + i) to (top + i, right)(top + i, right) to (bottom, right - i)(bottom, right - i) to (bottom - i, left)(bottom - i, left) to (top, left + i)Saving one value in a temporary variable lets us move the other three without losing data, so all four elements reach their correct positions in a single pass over the layer.
To confirm the indices, draw a 4x4 grid and trace one position through the rotation formula (i, j) -> (j, n - 1 - i) with n = 4. Starting at (0, 1): it moves to (1, 3), then (3, 2), then (2, 0), then back to (0, 1). Those four cells are exactly one four-way swap. The code writes them in the reverse order of this cycle: it caches the top element, fills it from the left, the left from the bottom, the bottom from the right, and the right from the cached top. Pulling values backward along the cycle moves each one forward into its rotated slot.
top, bottom, left, and right boundaries.Take matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], so n = 4. With two layers, this shows both the boundary shrink and the four-way swap.
Layer 0 has top = 0, bottom = 3, left = 0, right = 3. The loop runs for i = 0, 1, 2:
The entire outer ring is now in place: [[13,9,5,1],[8,..,..,2],[15,..,..,3],[16,12,8,4]], with the four corners and edges rotated. Then top becomes 1 and bottom becomes 2.
Layer 1 has top = 1, bottom = 2, left = 1, right = 2. The loop runs once, for i = 0:
Now top becomes 2 and bottom becomes 1, so top < bottom is false and the loop ends. The final matrix is [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]], the input rotated 90 degrees clockwise. Every element was written exactly once.