Problem overview
The function rotate receives a square matrix as an Array<IntArray> and turns it a quarter turn clockwise. It must do this in place, moving numbers inside matrix itself, and it returns nothing: the result is matrix after the call. The work should take O(n^2) time and O(1) extra space.
For the 3 by 3 matrix with rows 1 2 3, 4 5 6, 7 8 9, the rotated matrix 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 becomes the right column.
Approach
The simplest way to rotate is to build a second matrix and copy each cell matrix[i][j] to result[j][n - 1 - i]. That works but uses O(n^2) extra space, which the task forbids. Moving cells around the matrix in four-cell cycles is possible too, but the index arithmetic is easy to get wrong.
A cleaner idea is to build the rotation from two simple flips:
- Transpose: flip the matrix over its main diagonal, the cells whose row number equals their column number. Row
ibecomes columni. - Reverse every row.
After the transpose, row i holds what used to be column i, read from top to bottom. A clockwise turn needs that column read from bottom to top, so each row is then reversed. Both flips only swap numbers inside the matrix, so no second matrix is needed.
For the 3 by 3 example, the transpose gives:
1 4 7
2 5 8
3 6 9
Reversing each row turns 1 4 7 into 7 4 1, and so on, which is the answer shown above.
Step by step
- Store the size.
val n = matrix.size. The matrix is square, sonis both the number of rows and the number of columns. - Loop over the rows with
iin0 until nto start the transpose. - Loop over the columns right of the diagonal with
jini + 1 until n. Starting ati + 1visits every pair of mirror cells exactly once. Ifjstarted at 0, every pair would be swapped twice and the second swap would undo the first, leaving the matrix unchanged. - Save one cell.
val temp = matrix[i][j], because the next line overwrites that cell. - Swap. Copy
matrix[j][i]intomatrix[i][j], then puttempintomatrix[j][i]. Together with the previous step, these three lines swap the two cells without losing a number. - Loop over the rows again with
iin0 until n, now to reverse each one. - Reverse the row in place with
matrix[i].reverse().
The solution in Kotlin
class Solution {
fun rotate(matrix: Array<IntArray>) {
val n = matrix.size
for (i in 0 until n) {
for (j in i + 1 until n) {
val temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}
for (i in 0 until n) {
matrix[i].reverse()
}
}
}
Kotlin details worth knowing:
- Arrays are modified in place. An
Array<IntArray>is an array of references to row arrays. The function receives the same arrays the caller holds, so changingmatrix[i][j]changes the caller's matrix. That is why the function can return nothing, and why the parameter is not reassigned: parameters in Kotlin are read-only names, and assigning a new matrix tomatrixwouldn't compile, let alone reach the caller. reverse()againstreversed(). On anIntArray,reverse()turns the array around where it is.reversed()leaves the array alone and returns a newList<Int>. Withrow = intArrayOf(1, 4, 7),row.reversed()gives the list[7, 4, 1]androwis still[1, 4, 7]; afterrow.reverse()the array itself reads[7, 4, 1].- Swap with a temporary. Kotlin has no tuple-style swap on array cells, so a
tempvalue does the job. untilexcludes its end.i + 1 until nruns up ton - 1. Wheniis the last row, the range is empty and the inner loop does nothing.
Complexity
Time is O(n^2). The transpose visits about half of the n^2 cells, and the row reversals touch each cell once more. Extra space is O(1): the code keeps only n, the loop counters and one temp.
Edge cases and common mistakes
- Starting the inner loop at 0. Each pair is swapped twice and the matrix comes out unchanged. For the 2 by 2 matrix with rows
1 2and3 4, swapping every pair twice leaves exactly1 2and3 4. - A 1 by 1 matrix. The inner loop never runs, and reversing a one-element row changes nothing, so the matrix stays as it is. A matrix holding
-7still holds-7. - Reversing the columns instead of the rows. Transpose followed by a column reversal gives a counter-clockwise turn. The order here, transpose then reverse each row, is the clockwise one.
- Allocating a new matrix. Returning a fresh matrix doesn't help: the function returns nothing, and the checked result is
matrixitself. - Negative and repeated values. They need no special treatment, because the code only moves numbers and never compares them.
Testing
Try the 2 by 2 matrix with rows 1 2 and 3 4. After rotate it reads:
3 1
4 2
For the 4 by 4 matrix with rows 5 1 9 11, 2 4 8 10, 13 3 6 7 and 15 14 12 16, the result is:
15 13 2 5
14 3 4 1
12 6 8 9
16 7 10 11
