Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Swift: In-Place Transpose and Reverse in O(n²)

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

    SWIFT · MATRIX

    Rotate Image in Swift, explained

    Problem overview

    The method rotate receives a square matrix, an inout [[Int]] with n rows of n numbers, and turns it a quarter turn clockwise. It returns nothing: after the call, the caller's matrix holds the rotated numbers. The statement asks for O(n²) time and O(1) extra space, so building a second matrix is not allowed.

    For the matrix with rows [1, 2, 3], [4, 5, 6] and [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 becomes the right column.

    Approach: two flips make a turn

    Copying into a new matrix is easy: the number at row i, column j goes to row j, column n - 1 - i. That needs O(n²) extra space, which the statement rules out. Rotating cell by cell in groups of four also works, but it takes careful index arithmetic.

    The lesson uses a simpler observation: a clockwise quarter turn is the same as two simple flips.

    1. Transpose the matrix: flip it over its main diagonal, so each row becomes the column with the same number.
    2. Reverse every row.

    On the example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Row 0 is now 1, 4, 7, which is the left column of the original read from the top. A clockwise turn needs it read from the bottom, so reversing the row gives 7, 4, 1, the top row of the answer. Both flips only swap numbers that are already inside the matrix, so no extra space is needed.

    Step by step

    1. Store the size. matrix.count goes into a let named n. The matrix is square, so it is both the number of rows and the number of columns.
    2. Loop over the rows with i from 0 up to n - 1. This starts the transpose.
    3. Loop over the columns to the right of the diagonal with j from i + 1. The diagonal cells (row equals column) stay where they are, and each pair of mirror cells above and below it should be swapped once. Starting j at 0 would visit every pair twice, and the second swap would undo the first.
    4. Swap matrix[i][j] and matrix[j][i] in one line, using a tuple on each side of the =.
    5. Loop over the rows again to reverse them.
    6. Call reverse() on matrix[i], which reverses the row in place.

    The solution in Swift

    class Solution {
        func rotate(_ matrix: inout [[Int]]) {
            let n = matrix.count
            for i in 0..<n {
                for j in i + 1..<n {
                    (matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])
                }
            }
            for i in 0..<n {
                matrix[i].reverse()
            }
        }
    }
    

    Swift details worth knowing:

    • inout. Arrays are value types, so a normal parameter is a read-only copy. Marking the parameter inout lets the method change the caller's array, and the caller passes it with &, for example solution.rotate(&grid). The variable being passed must be a var.
    • The tuple swap. (matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j]) first builds a tuple from both current values, then assigns it to the two cells. No temporary variable is needed.
    • i + 1..<n is the range from i + 1 up to n - 1. In the last row, i + 1 equals n, and the range is simply empty. It is not an error, because the range's start is not above its end.
    • reverse() against reversed(). reverse() changes the array it is called on. reversed() doesn't change anything: it returns a new sequence, so calling it on a row would leave the matrix as it was.
    • Nested arrays. matrix[i].reverse() changes the row stored inside matrix, because the subscript gives write access to that row.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the reversal touches every cell once, so the total is a constant times n².

    Space: O(1) extra. The method only keeps n and the loop variables. The swaps and the reversals happen inside the matrix.

    Edge cases and common mistakes

    • A single cell. [[42]] stays [[42]]. The inner range 1..<1 is empty, and reversing a row of one number changes nothing.
    • Transposing the whole square. If the inner loop runs j over 0..<n, every pair is swapped twice. On the 3 by 3 example the matrix comes back as [[1, 2, 3], [4, 5, 6], [7, 8, 9]], unchanged.
    • Reversing before transposing. The order matters. Reversing the rows first and then transposing turns the matrix counterclockwise instead.
    • Using reversed(). It builds a new sequence and the row stays unchanged, so the second loop does nothing useful.
    • Even sizes. The method makes no distinction between odd and even n. In the 4 by 4 example, the corners move as the statement says: 5 goes to the top-right, 11 to the bottom-right, 16 to the bottom-left and 15 to the top-left.
    • Four turns. Applying the method four times returns the original matrix, a handy check for your own tests.

    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]].
    • [[42]] stays [[42]].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free