Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Scala: In-Place Transpose and Row Reversal

Practice O(n^2) Read the full explanation

You get a square grid matrix of integers, with n rows and n columns.

Rotate it a quarter turn clockwise, like turning a photo onto its right side.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

Work in place. Change the numbers inside matrix itself, and don't fill a new grid.

Your function returns nothing. Each example's output shows matrix after the function runs.

 

Example 1:

Input: matrix = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 6]
]
Output: [
  [8, 3, 4],
  [1, 5, 9],
  [6, 7, 2]
]
Explanation: The left column, read from the bottom up, is now the top row.
The top row is now the right column.
The 5 in the center stays where it is.

Example 2:

Input: matrix = [
  [-3, 8],
  [8, 0]
]
Output: [
  [8, -3],
  [0, 8]
]
Explanation: Each number moves to the next corner clockwise:
-3 goes to the top right,
the top-right 8 goes to the bottom right,
0 goes to the bottom left,
the bottom-left 8 goes to the top left.

Example 3:

Input: matrix = [
  [7]
]
Output: [
  [7]
]
Explanation: A single number has nowhere to move.

 

Constraints:

  • n is from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 9
    Ctrl + Enter to check

    SCALA · MATRIX

    Rotate Image in Scala, explained

    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:

    1. Transpose the matrix: flip it over its main diagonal, the cells whose row number equals their column number. Row i becomes column i.
    2. 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

    1. Store the size. val n = matrix.length is both the number of rows and the number of columns, since the matrix is square.
    2. Loop over the rows with i <- 0 until n to start the transpose.
    3. 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.
    4. Save matrix(i)(j) in temp. The next line overwrites it, so its number must be kept.
    5. Finish the swap. Copy matrix(j)(i) into matrix(i)(j), then put temp into matrix(j)(i).
    6. Loop over the rows again for the reversal.
    7. Reverse a row by swapping from both ends. The inner loop j <- 0 until n / 2 covers the first half of the row. Going further would swap each pair back. When n is odd, n / 2 rounds down, so the middle cell stays where it is, which is correct.
    8. Save matrix(i)(j) in temp, as in the transpose.
    9. Swap with the mirror cell. Copy matrix(i)(n - 1 - j) into matrix(i)(j), then put temp into matrix(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 row i, an Array[Int], and matrix(i)(j) is one number in it. Writing matrix(i)(j) = x changes 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 a for loop, which produces no value, so nothing is returned and nothing is missing.
    • reverse isn't in place. row.reverse builds and returns a new array and leaves row as it was. For Array(1, 2, 3) the original stays 1,2,3 while the reversed copy is 3,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.
    • for with until. 0 until n / 2 is an empty range when n / 2 is 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 j starting 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]].
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free