Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Kotlin: In-Place Transpose and Row Reverse

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 7
    Ctrl + Enter to check

    KOTLIN · MATRIX

    Rotate Image in Kotlin, explained

    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:

    1. Transpose: flip the matrix 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, 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

    1. Store the size. val n = matrix.size. The matrix is square, so n is both the number of rows and the number of columns.
    2. Loop over the rows with i in 0 until n to start the transpose.
    3. Loop over the columns right of the diagonal with j in i + 1 until n. Starting at i + 1 visits every pair of mirror cells exactly once. If j started at 0, every pair would be swapped twice and the second swap would undo the first, leaving the matrix unchanged.
    4. Save one cell. val temp = matrix[i][j], because the next line overwrites that cell.
    5. Swap. Copy matrix[j][i] into matrix[i][j], then put temp into matrix[j][i]. Together with the previous step, these three lines swap the two cells without losing a number.
    6. Loop over the rows again with i in 0 until n, now to reverse each one.
    7. 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 changing matrix[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 to matrix wouldn't compile, let alone reach the caller.
    • reverse() against reversed(). On an IntArray, reverse() turns the array around where it is. reversed() leaves the array alone and returns a new List<Int>. With row = intArrayOf(1, 4, 7), row.reversed() gives the list [7, 4, 1] and row is still [1, 4, 7]; after row.reverse() the array itself reads [7, 4, 1].
    • Swap with a temporary. Kotlin has no tuple-style swap on array cells, so a temp value does the job.
    • until excludes its end. i + 1 until n runs up to n - 1. When i is 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 2 and 3 4, swapping every pair twice leaves exactly 1 2 and 3 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 -7 still 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 matrix itself.
    • 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
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free