Blind 75 · Math & Geometry

Rotate Image

Medium

Watch the walkthrough (5:23)

Problem

Given an n x n matrix, rotate it 90 degrees clockwise: the first row becomes the last column, and the last row becomes the first column.
Do it in place: change the matrix you are given, and return nothing.

Examples

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]]

Example 3:
Input: matrix = [[1]]
Output: [[1]]

Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints

1 <= n <= 20
-1000 <= matrix[i][j] <= 1000

Prerequisites

Index arithmetic on a grid, and the discipline of writing the coordinate rule down before coding it.

How to think about it

1. Transpose, Then Reverse Each Row Optimal

Intuition

A quarter turn clockwise sends the value at (r, c) to (c, n-1-r), and two mirrors make that move without a second grid. The transpose mirrors the matrix in its main diagonal: (r, c) goes to (c, r), so row r becomes column r. Reversing each row mirrors it down the middle: column c goes to n-1-c. One after the other, (r, c) goes to (c, r) and then to (c, n-1-r), the rotation's own rule. Each mirror is a set of swaps, and a swap holds only one value aside, so the matrix turns in place. The order is the rule's: reversed first and transposed after, the matrix turns counterclockwise. Transpose the matrix, and after that, reverse each row.

Algorithm

1. Transpose: for every row i, and every column j after it (from i + 1), swap matrix[i][j] with matrix[j][i]. Starting past the diagonal swaps each pair once; the diagonal stays where it is.
2. Reverse each row: swap its first and last values, then the next pair in, up to the middle.
3. Return nothing: matrix is the rotation.

Time & Space

Time O(n^2): each value moves a fixed number of times, at most once in the transpose and at most once in the reverse. Space O(1): the swaps hold one value aside.

2. One Coordinate Rule

Intuition

Write the rule down before writing code: a clockwise quarter turn sends the value at (row, column) to (column, n-1-row). Written straight into the matrix, a value lands on a cell whose own value has not moved yet, and that value is lost. Filled into a fresh grid instead, the rule is a two-line loop that never overwrites anything it still needs, and then matrix is given the fresh grid's rows, which changes the matrix it was handed. It costs a second n x n grid, which the first approach does without.

Algorithm

1. Allocate an n x n grid, rotated.
2. For every (r, c), place matrix's value at (c, n-1-r) of rotated.
3. Give matrix the rows of rotated, one by one. Return nothing.

Time & Space

Time O(n^2). Space O(n^2): the second grid.