Rotate Image

Turn a square grid of numbers a quarter turn clockwise, changing the grid itself instead of building a new one.

Given a square grid of integers, matrix, with n rows and n columns, rotate it 90 degrees clockwise. Do it in place: change the rows of matrix itself, without building a second grid to hold the result.

Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Example 2
Input: matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
Output: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
Solution

The Idea

Turn your phone sideways while a photo is open, and the photo turns a quarter of the way round with it. On the screen, a photo is a grid of tiny coloured dots, and a program keeps those dots as a grid of numbers. Rotating the image means moving every number to its place in the turned grid.

Take Example 1, where row 0 holds 1, 2 and 3. After the turn, those three numbers stand in the last column, col 2, reading down: 1 in row 0, 2 in row 1 and 3 in row 2. The bottom row, 7, 8, 9, moves into col 0, so the new row 0 reads 7, 4, 1. In general, the number at row r, col c moves to row c, col n - 1 - r.

With a second grid, that rule is all you need. Here, though, the answer goes into the same grid. Writing 1 into row 0, col 2 would wipe out the 3 that sits there before the 3 has moved anywhere. So how can every number move without losing any of them?

Swapping two numbers never loses either one, so the turn has to be built out of swaps. Two flips do it. First, swap each number with its mirror image across the diagonal that runs from the top left corner to the bottom right, through 1, 5 and 9. This flip is called a transpose: it turns row 0 into col 0, row 1 into col 1, and so on. Then reverse each row.

Example 1 in three stages. Start: rows 1 2 3, 4 5 6, 7 8 9. After transpose: rows 1 4 7, 2 5 8, 3 6 9. After reversing each row: rows 7 4 1, 8 5 2, 9 6 3. The value 2 moves from row 0, col 1 to row 1, col 0, then to row 1, col 2.

The picture shows Example 1 in three stages. Follow the orange 2: it starts at row 0, col 1. The transpose moves it to row 1, col 0, and reversing row 1 moves it on to row 1, col 2, exactly where the rule above sends it. The teal cells, 1, 5 and 9, sit on the diagonal and stay put in the transpose.

The grid labelled "after reversing each row" reads 7, 4, 1, then 8, 5, 2, then 9, 6, 3, which is the expected output. Each of the two flips is only a series of swaps, so neither needs a second grid.

Solution Approach

A spare grid gives a simple answer that the problem does not allow, and the in-place version needs three choices: why the two flips equal one turn, which cells the transpose swaps, and how each row is reversed.

Rotating with a spare grid

What is the most direct way? Make a new n by n grid, copy each number from row r, col c to row c, col n - 1 - r, and then copy the new grid back into matrix. It gives the right answer, but it needs room for another n2 numbers, which is what doing it in place rules out.

Why two flips make a quarter turn

Can we be sure the two flips put every number where the rule says, and not just the 2? The transpose sends the number at row r, col c to row c, col r. Reversing row c keeps the number in that row and moves it from col r to col n - 1 - r. Together that is row c, col n - 1 - r, the rotation rule, for every cell.

Swapping only above the diagonal

Which cells should the transpose visit? If it visits every cell, the pair at row 0, col 1 and row 1, col 0 is swapped twice, once from each side. The second swap undoes the first, and the grid ends up as it started.

So in row r, the transpose visits only the columns from r + 1 on, which are the cells above the diagonal. Each pair is then swapped once, and the diagonal cells, which would only swap with themselves, are skipped.

Reversing a row in place

How is one row reversed without a spare row? Put one marker, left, on the first number and another, right, on the last. Swap the two numbers, step both markers toward the middle, and stop when they meet. In the row 2, 5, 8 from the "after transpose" grid, the 2 and the 8 swap places and the middle 5 stays where it is.

Java Solution

The method rotate works in these steps:

  1. First, store the size of the grid in n, from matrix.length.
  2. Transpose the grid with two loops, one inside the other. The outer loop moves r down the rows. For each r, the inner loop moves c from r + 1 to the last column and swaps matrix[r][c] with matrix[c][r], holding one of them in a temporary variable t.
  3. Then reverse each row. A loop takes each row of matrix in turn. Inside it, left starts at 0 and right at n - 1, and they swap their numbers and move toward each other while left is less than right.
  4. The method returns nothing, because the turned grid is now in matrix itself.

A small helper, rotateAndPrint, rotates a grid and prints it row by row under a label. The main method uses it on both examples, a 2 x 2 grid and a 1 x 1 grid, then turns Example 1 four times and checks that it is back where it started.

Java
import java.util.Arrays;

public class RotateImage {

    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int r = 0; r < n; r++) {               // 1. transpose
            for (int c = r + 1; c < n; c++) {       // only cells above the diagonal
                int t = matrix[r][c];
                matrix[r][c] = matrix[c][r];
                matrix[c][r] = t;
            }
        }
        for (int[] row : matrix) {                  // 2. reverse each row
            for (int left = 0, right = n - 1; left < right; left++, right--) {
                int t = row[left];
                row[left] = row[right];
                row[right] = t;
            }
        }
    }

    static void rotateAndPrint(String label, int[][] matrix) {
        rotate(matrix);
        System.out.println(label + ":");
        for (int[] row : matrix) {
            System.out.println("  " + Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        rotateAndPrint("Example 1", new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
        int[][] example2 = {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
        rotateAndPrint("Example 2", example2);
        rotateAndPrint("2 x 2", new int[][] {{1, 2}, {3, 4}});
        rotateAndPrint("1 x 1", new int[][] {{1}});

        int[][] start = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] turned = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        for (int turn = 0; turn < 4; turn++) {
            rotate(turned);
        }
        System.out.println("Four turns give back the start: " + Arrays.deepEquals(start, turned));
    }
}

Running it prints:

Output
Example 1:
  [7, 4, 1]
  [8, 5, 2]
  [9, 6, 3]
Example 2:
  [15, 13, 2, 5]
  [14, 3, 4, 1]
  [12, 6, 8, 9]
  [16, 7, 10, 11]
2 x 2:
  [3, 1]
  [4, 2]
1 x 1:
  [1]
Four turns give back the start: true

Under "Example 1", the rows [7, 4, 1], [8, 5, 2] and [9, 6, 3] are the last grid of the picture, and the four rows under "Example 2" match that example's expected output. The 2 x 2 grid [[1, 2], [3, 4]] comes out as [3, 1] over [4, 2]: its transpose swaps the single pair 2 and 3, and each row reversal swaps one pair.

The 1 x 1 grid prints [1] unchanged, because neither flip finds a pair to swap. The last line ends in true: four quarter turns bring Example 1 back to [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

Starting the inner transpose loop at c = 0 instead of r + 1 is an easy slip with a confusing result. A separate run of that version on Example 1 left the grid unchanged after the transpose, [[1, 2, 3], [4, 5, 6], [7, 8, 9]], because every pair was swapped twice. Reversing the rows then gave [[3, 2, 1], [6, 5, 4], [9, 8, 7]], a mirror image instead of a turn.

Complexity

Each flip handles every cell of the n by n grid at most once, and the extra storage is a few loop counters plus the temporary t.

  • Time: O(n2), because the transpose swaps each of the n(n - 1) / 2 pairs across the diagonal once, and the row reversal makes about n / 2 swaps in each of the n rows.
  • Space: O(1), because both flips swap numbers inside matrix itself and need only the variable t, while the spare-grid way would need room for n2 more numbers.

The first flip on its own is the subject of Transpose Matrix.