Rotate Image solution explained
To rotate an n by n matrix 90 degrees clockwise in place, transpose it (swap each cell with its mirror across the main diagonal) and then reverse every row. Both steps touch each cell a constant number of times, so the Rotate Image solution runs in O(n²) time with O(1) extra space, and it never needs a second grid.
By Evin JohnPublished 7 min read
The task, restated
You are given a square grid of numbers, for example the pixels of a small square image. Turn it a quarter turn clockwise, so the left column becomes the top row, read from the bottom up. The catch is that you must change the grid you were given. Allocating a second grid of the same size is not allowed in the strict version.
| Before | After a quarter turn clockwise |
|---|---|
| [[11, 12, 13], [14, 15, 16], [17, 18, 19]] | [[17, 14, 11], [18, 15, 12], [19, 16, 13]] |
| [["a", "b"], ["c", "d"]] | [["c", "a"], ["d", "b"]] |
| [[5]] | [[5]] |
| [] (empty) | [] |
Clarify three things: the direction (clockwise or counterclockwise), whether the grid is always square, and whether you may use extra memory. Non-square grids cannot be rotated in place at all, because the shape changes from rows by columns to columns by rows.
How interviewers use it
Rotate Image checks whether you can reason about indexes without drawing every cell, and whether you can turn an idea that needs extra memory into one that does not. It shows up in screens for teams that touch graphics, games, and anything with grids. Interviewers often let you start with the copy, then ask for in place, then ask you to prove the transpose step does not overwrite values it still needs.
- Rotate counterclockwise. Transpose, then reverse each column; or reverse each row first and then transpose.
- Rotate 180 degrees. Reverse the order of the rows and reverse each row. No transpose needed.
- Rotate by k quarter turns. Reduce k modulo 4 and apply the right combination once.
- Rectangular grid. Return a new grid of the swapped shape; in place is impossible, and saying so is the answer.
Brute force: build a rotated copy
Write down where one cell goes. In a clockwise quarter turn, the top row becomes the right column. So the cell at row r and column c lands at row c and column n - 1 - r. Allocate an empty n by n grid, place every cell, and copy back. O(n²) time and O(n²) extra space. It is the fastest way to a correct answer and a good reference for testing.
def rotate_copy(grid):
n = len(grid)
out = [[0] * n for _ in range(n)]
for r in range(n):
for c in range(n):
out[c][n - 1 - r] = grid[r][c]
return outIn place: transpose, then reverse each row
The mapping (r, c) to (c, n - 1 - r) is two simpler moves stacked. A transpose sends (r, c) to (c, r). Reversing a row sends column k to column n - 1 - k. Apply the transpose, then reverse each row, and (r, c) ends at (c, n - 1 - r), exactly the clockwise turn.
The transpose must swap each pair once. Loop over the cells above the diagonal only, with the column starting at r + 1. If you loop over every cell, each pair is swapped twice and the grid comes back unchanged.
def rotate_in_place(grid):
n = len(grid)
for r in range(n):
for c in range(r + 1, n):
grid[r][c], grid[c][r] = grid[c][r], grid[r][c]
for row in grid:
row.reverse()function rotateInPlace(grid) {
const n = grid.length;
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
[grid[r][c], grid[c][r]] = [grid[c][r], grid[r][c]];
}
}
for (const row of grid) row.reverse();
}Alternative: rotate ring by ring with four-way swaps
Some interviewers want a single pass. Treat the grid as nested square rings. For each position along the top edge of a ring, four cells trade places: top to right, right to bottom, bottom to left, left to top. Save the top value, then fill each spot from the one that rotates into it. It does the same O(n²) work in one sweep, but the index arithmetic is easy to get wrong, so trace a 4 by 4 example aloud.
def rotate_layers(grid):
n = len(grid)
for layer in range(n // 2):
first, last = layer, n - 1 - layer
for i in range(first, last):
off = i - first
top = grid[first][i]
grid[first][i] = grid[last - off][first]
grid[last - off][first] = grid[last][last - off]
grid[last][last - off] = grid[i][last]
grid[i][last] = topTime and space
| Version | Time | Extra space |
|---|---|---|
| Rotated copy | O(n²) | O(n²) |
| Transpose, then reverse rows | O(n²) | O(1) |
| Ring-by-ring four-way swaps | O(n²) | O(1) |
O(n²) is the floor: every cell except the center of an odd grid has to move, and there are n² cells.
Edge cases
- An empty grid: both loops do nothing.
- A 1 by 1 grid stays the same.
- Odd sizes: the center cell never moves, and the ring loop stops before it.
- Repeated values, which hide bugs: test with distinct values so a wrong mapping shows.
- Grids of strings or objects: the swaps work the same because only references move.
Mistakes to avoid
- Transposing over the whole grid, which swaps every pair twice and undoes itself.
- Reversing the order of the rows instead of the contents of each row, which gives the counterclockwise turn.
- Returning a new grid when the task says to modify the input. Ask, and say which one you are doing.
- Off-by-one errors in the ring version: the inner loop runs from first to last - 1, not to last.
- In Python, building the copy with
[[0] * n] * n, which repeats one row object n times.
How to explain it out loud
Fictional example
- Candidate
- In a clockwise turn, row r becomes column n minus 1 minus r. With a spare grid I would just place each cell there.
- Candidate
- To do it in place I split that mapping in two: a transpose swaps rows and columns, and reversing each row flips the columns. Together they give the same mapping.
- Candidate
- I only swap above the diagonal so each pair moves once. That is n squared time and constant extra space, and a counterclockwise turn would reverse columns instead of rows.
Related walkthroughs
Spiral Matrix walks the same rings this page swaps, reading them instead of moving them. Set Matrix Zeroes is another grid task where the in-place version is the real test. For grid traversal as graph search, see Number of Islands.
Where Natively fits
During practice on Mac or Windows, Natively can take a screenshot of a grid problem, read it and point you toward the transpose-and-reverse split, then help you check your indexes on a 4 by 4 case. It transcribes the mock session too, so you can hear whether your explanation of the mapping made sense before you wrote code. More on the AI interview assistant page.
Questions people ask
How do you rotate a matrix 90 degrees clockwise in place?
Transpose it by swapping each cell above the diagonal with its mirror, then reverse every row. Together the two steps move the cell at row r, column c to row c, column n minus 1 minus r.
What is the time complexity of Rotate Image?
O(n squared) for an n by n matrix, since every cell moves, with O(1) extra space for the in-place versions.
How do you rotate a matrix counterclockwise?
Transpose and then reverse each column, or reverse each row first and then transpose.
Can a rectangular matrix be rotated in place?
No. Its shape changes from rows by columns to columns by rows, so you must build a new matrix.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
