Start learning free

LESSON 331 OF 671 · MATRIX

Rotate Image in Java: 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 9
    Ctrl + Enter to check

    JAVA · MATRIX

    Rotate Image in Java, explained

    Problem overview

    The method rotate receives a square int[][] matrix with n rows and n columns and turns it a quarter turn clockwise. It must work in place: the numbers move inside matrix itself, nothing is returned, and no second matrix is built. Time is O(n²) and extra space is O(1).

    For the matrix [[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 flips make a rotation

    The direct way is to compute where each number lands. A number at row i, column j moves to row j, column n - 1 - i. Copying every number into a new matrix with that rule is easy, but it uses O(n²) extra space. Doing it in place means moving four numbers around a cycle at once, and that is easy to get wrong.

    There is a simpler route that splits the turn into two flips, each of which is a plain swap of pairs:

    1. Transpose the matrix: flip it over its main diagonal, the line from the top-left to the bottom-right corner. The number at row i, column j trades places with the one at row j, column i. Row i becomes what column i was.
    2. Reverse every row. A clockwise turn needs each old column read from the bottom up, and after the transpose that column sits in a row from the top down, so each row is read backwards.

    For the first example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Reversing each row then gives [[7, 4, 1], [8, 5, 2], [9, 6, 3]], the expected result.

    Step by step

    1. Store the size. int n = matrix.length; is both the number of rows and the number of columns, because the matrix is square.
    2. Loop over the rows with i from 0 to n - 1, for the transpose.
    3. Loop over the columns right of the diagonal with j from i + 1 to n - 1. This visits each pair of mirror cells once. Starting at 0 would visit each pair twice and the second swap would undo the first.
    4. Save matrix[i][j] in temp. The next line overwrites that cell, and its value must not be lost.
    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 to reverse each one.
    7. Loop j from 0 while j < n / 2. Java has no method that reverses an int[] in place, so the row is reversed by swapping its two ends and moving inward. Only the first half starts a swap. Going further would swap each pair back.
    8. Swap matrix[i][j] with matrix[i][n - 1 - j], again through temp. Cell n - 1 - j is the mirror of cell j within the row.

    The solution in Java

    class Solution {
        public void rotate(int[][] matrix) {
            int n = matrix.length;
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = temp;
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n / 2; j++) {
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[i][n - 1 - j];
                    matrix[i][n - 1 - j] = temp;
                }
            }
        }
    }
    

    The Java details worth a closer look:

    • A 2D array is an array of arrays. int[][] holds one reference per row, and matrix[i][j] reads row i, then column j in it. Because the method changes the rows that the caller's array refers to, the caller sees the rotated numbers after the call, and nothing needs to be returned.
    • No swap helper. Java cannot swap two int variables through a method, so the three-line pattern with temp is written inline. Collections.reverse would not help: it works on a List, not on an int[].
    • Odd sizes. When n is odd, n / 2 uses integer division and rounds down, so the middle cell of each row is not swapped with anything. That is correct, since it is its own mirror.
    • Same names, separate scopes. The variable temp is declared inside each inner loop body, so each swap gets a fresh one.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the row reversal visits another half of them. Each visit is a constant-time swap.

    Space: O(1). Only n, i, j and temp are added, whatever the size of the matrix.

    Edge cases and common mistakes

    • A 1 by 1 matrix. [[7]] stays [[7]]: the transpose loop has nothing right of the diagonal, and n / 2 is 0, so the reversal does nothing.
    • Transposing from column 0. If the inner loop starts at j = 0, every pair is swapped twice. On the 3 by 3 example, that leaves [[1, 2, 3], [4, 5, 6], [7, 8, 9]] unchanged, and the reversal then produces a wrong result.
    • Reversing the whole row. If the reversal loop runs while j < n, every pair is swapped twice. After the transpose, the matrix comes out as [[1, 4, 7], [2, 5, 8], [3, 6, 9]]: only the transpose has taken effect.
    • Transpose without reversing. A transpose alone is a reflection, not a rotation. The reversal is what turns it into a clockwise quarter turn.
    • Building a new matrix. Assigning matrix = new int[n][n] inside the method changes only the local parameter. The caller's matrix stays as it was, which is why the lesson swaps numbers inside the existing rows.

    Testing

    • [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
    • [[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]].
    • [[7]] stays [[7]].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free