Matrix · 8 of 10
Rotate matrix by 90 degrees
Turn a square grid a quarter turn clockwise without a second grid, by flipping it across its diagonal and then reversing every row.
- Simple way
- time O(n^2)
room O(n^2) - Clever way
- time O(n^2)
room O(1)
The problem, simply
You get an n by n grid of numbers. Turn it 90 degrees clockwise, like turning a photo on a table a quarter turn to the right.
Change the grid you were given. The hard version, and the one interviewers expect, says you may not make a second grid.
A story to remember it
Picture it
Turning clockwise: the top row 1, 2, 3 becomes the right column, and the left column, read from the bottom up as 7, 4, 1, becomes the top row.
- looking now
Examples
A 3 by 3 grid
- In
[[1,2,3],[4,5,6],[7,8,9]]- Out
[[7,4,1],[8,5,2],[9,6,3]]
The first row becomes the last column. The first column, read from the bottom up, becomes the first row.
A 4 by 4 grid
- In
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]- Out
[[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]]
An even size has no middle cell. Two rings turn.
A 2 by 2 grid
- In
[[1,2],[3,4]]- Out
[[3,1],[4,2]]
All four cells are corners, and each moves one corner clockwise.
One cell
- In
[[5]]- Out
[[5]]
Turning one cell changes nothing.
Way 1: the simple way
Make a new empty grid and copy each number to where it belongs after the turn. A number at row i, column j moves to row j, column n - 1 - i. Then copy the new grid back.
- For every cell
(i, j):rotated[j][n - 1 - i] = matrix[i][j]. - Copy
rotatedback intomatrix.
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
rotated[j][n - 1 - i] = matrix[i][j]; // row i becomes column n - 1 - i
for (int i = 0; i < n; i++)
matrix[i] = rotated[i].clone(); // copy back into the given grid
}
}How long it takes: every cell is moved once and copied once, O(n^2). Extra room: a whole second grid, O(n^2).
Way 2: the clever way
A turn is two flips, and a flip only swaps pairs, so it needs no second grid.
- Flip across the main diagonal (this is called the transpose). For every pair
i < j, swapmatrix[i][j]withmatrix[j][i]. Now each old row is a column. - Reverse every row. Swap the ends and walk inward.
Why it works: the flip moves (i, j) to (j, i). Reversing the row moves (j, i) to (j, n - 1 - i). Together that is (i, j) to (j, n - 1 - i), the same place as in Way 1.
Flip across the diagonal, then reverse each row
01 / 07
Goal: the top row 1, 2, 3 must end up as the right column. Step one is a mirror flip across the grey line from the top left to the bottom right. The cells on that line stay put.
- looking now
- seen
- done
- answer
- ignored
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) { // step 1: flip across the diagonal
for (int j = i + 1; j < n; j++) { // j starts at i + 1, so each pair swaps once
int t = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = t;
}
}
for (int[] row : matrix) { // step 2: reverse each row
for (int l = 0, r = n - 1; l < r; l++, r--) {
int t = row[l];
row[l] = row[r];
row[r] = t;
}
}
}
}How long it takes: each step touches every cell at most once, O(n^2). Extra room: one temporary number, O(1).
Another way: four cells at a time
You can also turn the grid ring by ring, like turning the outer ring of a combination lock. In each ring, cells come in groups of four (one on each side). Hold one number in your hand, slide the other three one place clockwise, and put the held number down. Every cell moves only once.
Turn four cells at a time, ring by ring
01 / 05
A 4 by 4 grid has two rings: the shaded outer ring and the inner ring 6, 7, 10, 11. We turn one ring at a time, four cells at a time.
- layer
- 0
- looking now
- done
- path
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer, last = n - 1 - layer;
for (int i = first; i < last; i++) {
int off = i - first;
int top = matrix[first][i]; // hold the top one
matrix[first][i] = matrix[last - off][first]; // left goes to top
matrix[last - off][first] = matrix[last][last - off]; // bottom goes to left
matrix[last][last - off] = matrix[i][last]; // right goes to bottom
matrix[i][last] = top; // top goes to right
}
}
}
}Same O(n^2) time and O(1) room, with fewer writes (each cell is written once instead of twice). It is easier to get an index wrong, so the two flips are the safer choice under pressure.
Watch out for
- Doing the steps in the other order for clockwise. Reverse rows first, then flip, gives a counter clockwise turn.
- Reversing columns instead of rows after the flip. That also gives counter clockwise.
- A grid that is not square. A 2 by 3 grid turns into a 3 by 2 grid, so it cannot be done in place; make a new grid as in Way 1.
What interviewers ask next
- Counter clockwise? Flip across the diagonal, then reverse each column. Or reverse each row first, then flip.
- 180 degrees? Reverse the order of the rows, then reverse each row. Or turn clockwise twice.
- Turn by
kquarter turns? Onlyk % 4matters. 0 is nothing, 2 is the 180 turn, 3 is counter clockwise. - Check whether one grid is a rotation of another. Turn it up to 3 times and compare after each turn,
O(n^2). - Flip across the other diagonal (top right to bottom left)? Swap
matrix[i][j]withmatrix[n-1-j][n-1-i].
Remember this
Grown-up words: the fold along the diagonal is the transpose, reversing a row is a horizontal reflection, two reflections make a rotation, and the four cell slide is a cyclic swap of the matrix layers.