Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Rust: Transpose, Then Reverse Each Row

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

    RUST · MATRIX

    Rotate Image in Rust, explained

    Problem overview

    The function rotate receives matrix, a &mut Vec<Vec<i32>> holding a square grid of n rows and n columns. It must turn the grid a quarter turn clockwise, in place, and return nothing: the caller sees the rotated numbers in its own matrix. The time budget is O(n²) and the extra space O(1), so building a second matrix is not allowed.

    For the grid [[1, 2, 3], [4, 5, 6], [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 (1, 2, 3) becomes the right column.

    Approach: two simple flips make a rotation

    Rotating directly means moving numbers in cycles of four: the top-left corner goes to the top-right, that one to the bottom-right, and so on. That works, but the index arithmetic is easy to get wrong.

    The lesson uses a cleaner decomposition. First transpose the matrix: mirror it over its main diagonal, so the number at row i, column j moves to row j, column i. Then reverse every row. Together the two flips equal one clockwise quarter turn, and both only swap numbers inside the matrix.

    On the example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Each row is the old column with the same number, read from top to bottom. A clockwise turn needs each of those columns read from bottom to top, so reversing every row finishes the job: the first row [1, 4, 7] becomes [7, 4, 1].

    Step by step

    1. Store the size matrix.len() in n. The matrix is square, so it is both the row count and the column count.
    2. Loop over the rows with i going over 0..n, to start the transpose.
    3. Loop over the columns to the right of the diagonal with j going over i + 1..n. Each pair of mirror cells is visited exactly once.
    4. Save matrix[i][j] in temp, because the next line overwrites that cell.
    5. Finish the swap: copy matrix[j][i] into matrix[i][j], then put temp into matrix[j][i].
    6. Start a second loop over the rows, 0..n, for the reversal.
    7. Reverse the row matrix[i] in place with its reverse() method.

    The solution in Rust

    impl Solution {
        fn rotate(matrix: &mut Vec<Vec<i32>>) {
            let n = matrix.len();
            for i in 0..n {
                for j in i + 1..n {
                    let temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = temp;
                }
            }
            for i in 0..n {
                matrix[i].reverse();
            }
        }
    }
    

    The Rust details worth a closer look:

    • &mut is a mutable borrow. The function doesn't own the matrix; it borrows it and may change it. Writing to matrix[i][j] changes the caller's data, which is why nothing needs to be returned.
    • The manual swap. The three lines with temp copy an i32, which is a cheap, copyable value. Rust's borrow rules also explain why the swap is written this way: std::mem::swap(&mut matrix[i][j], &mut matrix[j][i]) would need two mutable borrows of matrix at the same time, and the compiler rejects that.
    • i + 1..n parses as (i + 1)..n. When i + 1 equals n the range is empty and the inner loop simply doesn't run.
    • reverse() is a method of slices that Vec can call. It reverses the elements where they are, without allocating, and it works here because matrix[i] is reached through a mutable reference.
    • Row-first indexing. matrix[i][j] is row i, column j: the outer vector holds rows, and each row is an inner vector.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, one swap per pair. The reversal touches every cell once. Both are proportional to n².

    Space: O(1) extra. The code uses n, the loop counters and one temp. Every number moves inside the existing matrix.

    Edge cases and common mistakes

    • A 1 by 1 matrix. The inner loop never runs and reversing a single element changes nothing, so [[-5]] stays [[-5]].
    • Starting the inner loop at 0. Then every pair is swapped twice, and the second swap undoes the first. On the 3 by 3 example the matrix comes back unchanged: [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
    • The order of the flips. Transpose first, then reverse the rows, gives a clockwise turn. Reversing the rows first and transposing afterwards would turn the matrix the other way, counterclockwise.
    • Reversing columns instead of rows. After the transpose, it is the rows that must be read backwards. Reversing the columns gives a different arrangement.
    • Building a new matrix. Copying into a fresh Vec<Vec<i32>> and assigning it back would be correct but uses O(n²) space, which the lesson rules out.
    • Even and odd sizes. The two-flip method needs no special case for the center cell of an odd-sized matrix: it sits on the diagonal and is never swapped.

    Testing

    • [[1, 2], [3, 4]] gives [[3, 1], [4, 2]].
    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives [[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]] gives [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]].
    • Calling rotate four times on [[1, 2], [3, 4]] gives [[1, 2], [3, 4]] again: four quarter turns make a full circle.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free