Example 1
ready- Input
matrix = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]- Expected
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]- Why
- the bottom row becomes the left-to-right first column after a clockwise turn
Turn a square photo to the right, and its top row becomes its right column.
You're given an n x n integer matrix. Rotate it 90 degrees clockwise and return the
rotated matrix.
Every input cell must appear once in the result. Rows become columns, and their order changes with the turn: the bottom-left value moves to the top-left, while the original top-left value moves to the top-right.
You may rearrange the input matrix itself. Either way, return the finished matrix so the result can be checked.
1 <= n <= 100matrix has exactly n rows, and every row has exactly n values.-1_000 <= matrix[i][j] <= 1_000Hints
A value at row i, column j lands at row j, column n - 1 - i. A fresh matrix
makes that rule direct to implement.
First swap values across the main diagonal, turning rows into columns. Then reverse every row. Try those two moves on a 3×3 grid by hand.
During the diagonal swap, visit only cells above the diagonal (j > i). Visiting
both halves would swap each pair twice and undo the work.
Can you perform the rotation with O(1) extra working space?
Visible cases
matrix = [
[
1,
2,
3
],
[
4,
5,
6
],
[
7,
8,
9
]
][
[
7,
4,
1
],
[
8,
5,
2
],
[
9,
6,
3
]
]matrix = [
[
1
]
][
[
1
]
]matrix = [
[
1,
2
],
[
3,
4
]
][
[
3,
1
],
[
4,
2
]
]Interview signal
The coordinate rule says exactly where every value goes: cell (row, col) moves to
(col, n - 1 - row). Write each value into a fresh square matrix, then return it.
def rotate(matrix: list[list[int]]) -> list[list[int]]:
n = len(matrix)
rotated = [[0] * n for _ in range(n)]
for row in range(n):
for col in range(n):
rotated[col][n - 1 - row] = matrix[row][col]
return rotatedTime O(n²) — each cell moves once. Space O(n²) for the new matrix.
A transpose swaps rows with columns by reflecting values across the main diagonal. After that reflection, reversing each row points those columns in the clockwise direction we need.
def rotate(matrix: list[list[int]]) -> list[list[int]]:
n = len(matrix)
for row in range(n):
for col in range(row + 1, n):
matrix[row][col], matrix[col][row] = (
matrix[col][row],
matrix[row][col],
)
for row in matrix:
row.reverse()
return matrixOnly the cells above the diagonal are visited during the transpose. Each swap fixes two positions, and the diagonal stays where it is. Row reversal then completes the turn.
Time O(n²) — the transpose and reversals each touch O(n²) values. Space O(1) beyond the returned matrix.
LeetCode's version mutates the matrix in place and returns void; ours returns the matrix so the judge can compare it.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
[
[
7,
4,
1
],
[
8,
5,
2
],
[
9,
6,
3
]
]