Problem overview
The method Rotate receives a square matrix as an int[][]: an array of n rows, each an array of n integers. It must turn the matrix a quarter turn clockwise, in place, and return nothing. The caller sees the rotated numbers in the same matrix object. The method should run in O(n²) time and use O(1) extra space.
For {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} the result is {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}. The left column read from the bottom up, 7, 4, 1, becomes the top row, and the top row 1, 2, 3 becomes the right column.
Approach: two simple flips
Building a second matrix and copying each value to its rotated position is easy, but it needs O(n²) extra space, which the lesson rules out. Moving each value straight to its final cell in place is possible (it means rotating four cells at a time), but the index arithmetic is easy to get wrong.
A cleaner route uses two reflections that are each easy to do in place:
- Transpose the matrix: reflect it over its main diagonal, so the value at row
i, columnjmoves to rowj, columni. Rows become columns. - Reverse every row.
Together they make a clockwise quarter turn. For the 3x3 example, the transpose gives {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}. The first row, 1, 4, 7, was the first column read top to bottom. A clockwise turn needs that column read from the bottom up, so reversing the row gives 7, 4, 1, the first row of the answer. Every other row works the same way.
Step by step
- Store the size.
matrix.Lengthis the number of rows, and since the matrix is square, it is also the number of columns. Call itn. - Loop over the rows with
ifrom 0 ton - 1for the transpose. - Loop over the columns to the right of the diagonal, with
jstarting ati + 1. Each pair of mirrored cells is visited once. Ifjstarted at 0, every pair would be swapped twice, and the second swap would undo the first. Cells on the diagonal map to themselves, so they need no swap. - Swap
matrix[i][j]andmatrix[j][i]with a tuple assignment, so no temporary variable is needed. - Loop over the rows again and reverse each one with
Array.Reverse, which works on the row array where it is.
The solution in C#
class Solution {
public void Rotate(int[][] matrix) {
int n = matrix.Length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j]);
}
}
for (int i = 0; i < n; i++) {
Array.Reverse(matrix[i]);
}
}
}
C# details worth knowing:
- Tuple swap. The right-hand side
(matrix[j][i], matrix[i][j])builds a tuple holding both current values before anything is assigned. The left-hand side then assigns them to the two cells in the other order. This is the idiomatic swap in modern C#. - Jagged array.
int[][]is an array of arrays, indexedmatrix[i][j]. That is different from the rectangularint[,], which is indexedmatrix[i, j]and has no row arrays to reverse. - In-place reversal.
Array.Reverse(array)reverses the array it receives and returns nothing. Becausematrix[i]is a reference to the actual row, the matrix itself changes. In a standalone fileArrayneedsusing System;. - Rows are references. Swapping single cells between rows works because each row is its own array. The caller's matrix is changed, which is what the lesson wants.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the reversal touches every cell once. Both are proportional to the number of cells.
Space: O(1). The tuple swap and the reversal need only a constant number of temporary values, and no second matrix is created.
Edge cases and common mistakes
- 1x1 matrix. The inner loop never runs and reversing a one-element row changes nothing, so
{{7}}stays{{7}}. - 2x2 matrix.
{{1, 2}, {3, 4}}becomes{{3, 1}, {4, 2}}. - Even and odd sizes. The same code handles both; the center cell of an odd matrix is on the diagonal and stays put.
- Starting
jat 0. Every pair is swapped twice and the matrix returns to its original form after the first loop. - Reversing each row before the transpose. The same two steps in the other order turn the matrix counterclockwise:
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}would end as{{3, 6, 9}, {2, 5, 8}, {1, 4, 7}}. Transpose first for a clockwise turn. - Returning a new matrix. The method is
voidand the caller reads the same array, so assigningmatrix = newMatrixinside the method changes only a local variable and the caller sees nothing.
Testing
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}becomes{{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}.{{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}}becomes{{15, 13, 2, 5}, {14, 3, 4, 1}, {12, 6, 8, 9}, {16, 7, 10, 11}}.{{1, 2}, {3, 4}}becomes{{3, 1}, {4, 2}}.{{7}}stays{{7}}.
