Problem overview
The method rotate receives a square matrix, Array[Array[Int]] with n rows and n columns, and turns it a quarter turn clockwise. It returns Unit: the matrix itself is rewritten, and the numbers move inside it without a second matrix.
For this matrix:
1 2 3
4 5 6
7 8 9
the result after the call 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 make one rotation
The direct way to rotate is to build a new n by n matrix and copy each number to its new place: the number in row i, column j goes to row j, column n - 1 - i. That is O(n²) time but also O(n²) extra space, which the lesson rules out. Moving numbers around the center in cycles of four works in place, but its index arithmetic is easy to get wrong.
A simpler in-place route uses two flips that each swap pairs of cells:
- Transpose the matrix: flip it over its main diagonal, the cells whose row number equals their column number. Row
ibecomes columni. - Reverse every row.
After the transpose, the example looks like this:
1 4 7
2 5 8
3 6 9
Row 0 is now 1, 4, 7, which is the original first column read from the top. A clockwise turn needs that column from the bottom up, so reversing each row gives 7, 4, 1, then 8, 5, 2, then 9, 6, 3, the expected answer. Both steps only swap cells inside the matrix, so the extra space is O(1) and the time is O(n²).
Step by step
- Store the size.
val n = matrix.lengthis both the number of rows and the number of columns, since the matrix is square. - Loop over the rows with
i <- 0 until nto start the transpose. - Loop over the columns to the right of the diagonal with
j <- i + 1 until n. Each pair of mirrored cells above and below the diagonal is visited once. Starting at 0 would swap every pair twice, and the second swap would undo the first. - Save
matrix(i)(j)intemp. The next line overwrites it, so its number must be kept. - Finish the swap. Copy
matrix(j)(i)intomatrix(i)(j), then puttempintomatrix(j)(i). - Loop over the rows again for the reversal.
- Reverse a row by swapping from both ends. The inner loop
j <- 0 until n / 2covers the first half of the row. Going further would swap each pair back. Whennis odd,n / 2rounds down, so the middle cell stays where it is, which is correct. - Save
matrix(i)(j)intemp, as in the transpose. - Swap with the mirror cell. Copy
matrix(i)(n - 1 - j)intomatrix(i)(j), then puttempintomatrix(i)(n - 1 - j).
The solution in Scala
class Solution {
def rotate(matrix: Array[Array[Int]]): Unit = {
val n = matrix.length
for (i <- 0 until n) {
for (j <- i + 1 until n) {
val temp = matrix(i)(j)
matrix(i)(j) = matrix(j)(i)
matrix(j)(i) = temp
}
}
for (i <- 0 until n) {
for (j <- 0 until n / 2) {
val temp = matrix(i)(j)
matrix(i)(j) = matrix(i)(n - 1 - j)
matrix(i)(n - 1 - j) = temp
}
}
}
}
Scala details worth knowing:
- A matrix is an array of arrays.
matrix(i)is rowi, anArray[Int], andmatrix(i)(j)is one number in it. Writingmatrix(i)(j) = xchanges the array the caller passed in, because arrays are mutable and passed by reference. That is why the method needs no return value. - The method's type is
Unit. The body ends with aforloop, which produces no value, so nothing is returned and nothing is missing. reverseisn't in place.row.reversebuilds and returns a new array and leavesrowas it was. ForArray(1, 2, 3)the original stays1,2,3while the reversed copy is3,2,1. The lesson swaps by hand to stay in place.- Swapping needs a temporary. Without
temp, the first assignment would destroy a value before it could be copied. Scala has no built-in swap for array cells. forwithuntil.0 until n / 2is an empty range whenn / 2is 0, so for a 1 by 1 matrix the reversal loop does nothing.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the reversal swaps about half of each row. The matrix has n² numbers, so any solution has to touch each one at least once.
Space: O(1). The method keeps n, the loop counters and one temp, however big the matrix is.
Edge cases and common mistakes
- A 1 by 1 matrix.
Array(Array(-5))stays as it is. Both inner loops are empty. - A 2 by 2 matrix.
[[1,2],[3,4]]becomes[[3,1],[4,2]]: every number moves one corner clockwise. - An odd size. In the 3 by 3 example, the center 5 never moves, and the middle cell of each row is skipped by the reversal.
- Transposing with
jstarting at 0. Every pair gets swapped twice, so the matrix comes out unchanged: the 3 by 3 example still reads 1 2 3, 4 5 6, 7 8 9 afterwards. - Reversing with
j <- 0 until n. Each pair of cells is swapped, then swapped back, so the rows come out as they were. - Doing the steps in the other order or skipping one. A transpose alone gives a mirror image, not a rotation; the reversal turns it into a quarter turn clockwise. Reversing the columns instead of the rows after the transpose would rotate the other way.
Testing
- The 3 by 3 example above gives
7 4 1,8 5 2,9 6 3. - The 4 by 4 matrix
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]gives[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]. [[1,2],[3,4]]gives[[3,1],[4,2]].[[-5]]gives[[-5]].
