Rotate Image: four cells, one cycle
Problem. Given an n × n matrix, rotate it 90 degrees clockwise in
place — no second matrix allowed.
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
The whole answer, before any explanation: every element walks one step along the orange arrow, and the element in the middle never moves.
\begin{tikzpicture}[font=\large]
\draw[step=1,thick,black!50] (0,0) grid (3,3);
\node at (0.5,2.5) {1}; \node at (1.5,2.5) {2}; \node at (2.5,2.5) {3};
\node at (0.5,1.5) {4}; \node at (1.5,1.5) {5}; \node at (2.5,1.5) {6};
\node at (0.5,0.5) {7}; \node at (1.5,0.5) {8}; \node at (2.5,0.5) {9};
\draw[->,very thick,orange] (3.4,1.5) -- (4.6,1.5);
\draw[step=1,thick,black!50] (5,0) grid (8,3);
\node at (5.5,2.5) {7}; \node at (6.5,2.5) {4}; \node at (7.5,2.5) {1};
\node at (5.5,1.5) {8}; \node at (6.5,1.5) {5}; \node at (7.5,1.5) {2};
\node at (5.5,0.5) {9}; \node at (6.5,0.5) {6}; \node at (7.5,0.5) {3};
\end{tikzpicture}
The one idea: every element knows exactly where it goes
Rotating the image moves the element at row i, column j to row j,
column n-1-i:
\[ \text{new}[j][n-1-i] = \text{old}[i][j] \]
So the top-left corner (0, 0) lands on the top-right (0, n-1), the
top-right lands on the bottom-right (n-1, n-1), the bottom-right lands on
the bottom-left (n-1, 0), and the bottom-left comes home to (0, 0).
Apply that map four times and you are back where you started — \(f^4\) is the identity — so every element belongs to an orbit of at most four cells, and rotating the matrix means walking each orbit once. The trick is that you can walk it in place: hold one value in a temporary, shift the other three forward, and drop the held value into the freed slot.
Why the copy is too expensive
The naive version allocates a fresh n × n matrix and writes each element to
its destination:
rotated = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - 1 - i] = matrix[i][j]
That is \(O(n^2)\) time and \(O(n^2)\) extra space — and the space is the part that hurts. A \(10^4 \times 10^4\) image holds \(10^8\) cells, so the copy needs hundreds of megabytes just to hold a rearrangement of data you already have. Every later version must remove exactly this cost: the extra matrix.
First rung: transpose, then reverse each row
Look closely at the destination formula. It factors into two familiar
operations. Transposing across the main diagonal sends (i, j) to (j, i):
\[ t[j][i] = m[i][j] \]
and reversing row j sends (j, i) to (j, n-1-i):
\[ r[j][n-1-i] = t[j][i] = m[i][j] \]
The composition is exactly the rotation map. Both steps are easy to do in place — swap across the diagonal, then two-pointer-reverse each row:
def rotate(matrix):
n = len(matrix)
for i in range(n): # transpose across the main diagonal
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix: # reverse each row
row.reverse()
This is already \(O(n^2)\) time and \(O(1)\) space, and it is the version to reach for when you cannot see the cycles. Its weakness is that every element is touched twice — once by the transpose, once by the reversal — and the two passes obscure what is really a single permutation.
The optimal version: walk each 4-cycle directly
Process the matrix one layer at a time (the outer ring, then the ring
inside it, and so on — n // 2 layers), and within a layer rotate each
4-cycle with one temporary:
def rotate(matrix):
# (i, j) -> (j, n-1-i): each orbit is a 4-cycle, rotate it in place
n = len(matrix)
for i in range(n // 2): # one layer at a time
for j in range(i, n - 1 - i): # one 4-cycle at a time
tmp = matrix[i][j]
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = tmp
Read the four assignments as one sentence: the left value moves to the top, the bottom value moves to the left, the right value moves to the bottom, and the saved top value moves to the right. Each element is written exactly once.
Dry run on [[1,2,3],[4,5,6],[7,8,9]]
Legend, stated once: orange cells are the four being swapped right now, green cells are already in their final position.
Step 1 — the corner cycle. i = 0, j = 0: tmp = 1. The arrows show where
each value travels — 1 → (0,2), 3 → (2,2), 9 → (2,0), 7 → (0,0).
\begin{tikzpicture}[font=\large]
\fill[orange!25] (0,2) rectangle ++(1,1);
\fill[orange!25] (2,2) rectangle ++(1,1);
\fill[orange!25] (2,0) rectangle ++(1,1);
\fill[orange!25] (0,0) rectangle ++(1,1);
\draw[step=1,thick,black!50] (0,0) grid (3,3);
\node at (0.5,2.5) {1}; \node at (1.5,2.5) {2}; \node at (2.5,2.5) {3};
\node at (0.5,1.5) {4}; \node at (1.5,1.5) {5}; \node at (2.5,1.5) {6};
\node at (0.5,0.5) {7}; \node at (1.5,0.5) {8}; \node at (2.5,0.5) {9};
\draw[->,very thick,orange] (0.9,2.75) -- (2.1,2.75);
\draw[->,very thick,orange] (2.75,2.1) -- (2.75,0.9);
\draw[->,very thick,orange] (2.1,0.25) -- (0.9,0.25);
\draw[->,very thick,orange] (0.25,0.9) -- (0.25,2.1);
\end{tikzpicture}
After the four writes the corners read 7, 1, 3, 9 clockwise from the top
left: matrix[0][0] = 7, matrix[0][2] = 1, matrix[2][2] = 3,
matrix[2][0] = 9.
Step 2 — the edge cycle. i = 0, j = 1: tmp = 2. The corners are done
(green); the four edge cells form their own cycle — 2 → (1,2),
6 → (2,1), 8 → (1,0), 4 → (0,1).
\begin{tikzpicture}[font=\large]
\fill[green!30] (0,2) rectangle ++(1,1);
\fill[green!30] (2,2) rectangle ++(1,1);
\fill[green!30] (2,0) rectangle ++(1,1);
\fill[green!30] (0,0) rectangle ++(1,1);
\fill[orange!25] (1,2) rectangle ++(1,1);
\fill[orange!25] (2,1) rectangle ++(1,1);
\fill[orange!25] (1,0) rectangle ++(1,1);
\fill[orange!25] (0,1) rectangle ++(1,1);
\draw[step=1,thick,black!50] (0,0) grid (3,3);
\node at (0.5,2.5) {7}; \node at (1.5,2.5) {2}; \node at (2.5,2.5) {1};
\node at (0.5,1.5) {4}; \node at (1.5,1.5) {5}; \node at (2.5,1.5) {6};
\node at (0.5,0.5) {9}; \node at (1.5,0.5) {8}; \node at (2.5,0.5) {3};
\draw[->,very thick,orange] (1.75,2.3) -- (2.3,1.75);
\draw[->,very thick,orange] (2.3,1.25) -- (1.75,0.7);
\draw[->,very thick,orange] (1.25,0.7) -- (0.7,1.25);
\draw[->,very thick,orange] (0.7,1.75) -- (1.25,2.3);
\end{tikzpicture}
Step 3 — the center holds still. Both cycles are green, and (1, 1) = 5
maps to itself under \((i,j) \to (j,\ n{-}1{-}i)\) — for odd n the middle cell
is a 1-cycle, so the loop bounds (n // 2 layers) correctly never touch it.
\begin{tikzpicture}[font=\large]
\foreach \x/\y in {0/0,1/0,2/0,0/1,2/1,0/2,1/2,2/2} { \fill[green!30] (\x,\y) rectangle ++(1,1); }
\draw[step=1,thick,black!50] (0,0) grid (3,3);
\node at (0.5,2.5) {7}; \node at (1.5,2.5) {4}; \node at (2.5,2.5) {1};
\node at (0.5,1.5) {8}; \node at (1.5,1.5) {5}; \node at (2.5,1.5) {2};
\node at (0.5,0.5) {9}; \node at (1.5,0.5) {6}; \node at (2.5,0.5) {3};
\end{tikzpicture}
The finished artifact, so you can verify without re-reading the diagrams:
7 4 1
8 5 2
9 6 3 ← answer
Why this is the rotation you already know
It is easy to memorize the index formula without believing it. Shifting to centered coordinates \(u = i - c\), \(v = j - c\) (with \(c = (n-1)/2\)) turns the map into the ordinary 90° clockwise rotation from linear algebra:
\[ \begin{pmatrix} u' \\ v' \end{pmatrix} = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \begin{pmatrix} u \\ v \end{pmatrix}, \qquad (u, v) \mapsto (v, -u) \]
Check the corner: \((0,0)\) centers to \((-1,-1)\), which maps to \((-1,1)\) — uncentered, \((0, 2)\). The matrix you memorized in a math class and the index juggling here are the same transformation; the \(n{-}1{-}i\) is just the un-centering.
The code in Go
func rotate(matrix [][]int) {
// (i, j) -> (j, n-1-i): each orbit is a 4-cycle, rotate it in place
n := len(matrix)
for i := 0; i < n/2; i++ { // one layer at a time
for j := i; j < n-1-i; j++ { // one 4-cycle at a time
tmp := matrix[i][j]
matrix[i][j] = matrix[n-1-j][i]
matrix[n-1-j][i] = matrix[n-1-i][n-1-j]
matrix[n-1-i][n-1-j] = matrix[j][n-1-i]
matrix[j][n-1-i] = tmp
}
}
}
Same loop bounds, same names, same four writes — a straight port, with integer
division n/2 matching Python’s n // 2 for the layer count.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Fresh copy | \(O(n^2)\) | \(O(n^2)\) |
| Transpose + reverse rows | \(O(n^2)\) | \(O(1)\) |
| 4-cycle per layer | \(O(n^2)\) | \(O(1)\) |
Every in-place version visits each of the \(n^2\) cells a constant number of times — twice for transpose-plus-reverse, exactly once for the 4-cycle, which is why the direct walk is the version to present.
Edge cases
- Empty matrix (
[]):n = 0, both loop ranges are empty, nothing happens — no guard needed, but confirm it returns cleanly. 1 × 1matrix ([[5]]): the single element maps to itself andrange(n // 2)is empty, so it stays[[5]].- Odd
n: the center cell (e.g.(1, 1)above) is a 1-cycle and is never touched; then // 2layers stop exactly one ring short of it. - Rectangular input: an
m × nrotation needs a newn × mshape, so it cannot be done in place — the problem guarantees a square matrix, and the fresh-copy version is the fallback when it is not.
Transposing across the other diagonal (then reversing columns) rotates counter-clockwise, and the layer-walking habit here is the same one Spiral Matrix demands.