Rotate Image
Rotate Image
You are given an n x n matrix. Rotate it 90 degrees clockwise in-place.
Function signature
func RotateImage(matrix [][]int)
Inputs / outputs
matrix: square matrix to rotate in-place.- Return: nothing; modify
matrix.
Example
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
After rotation:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Constraints
1 <= n <= 1000
Core idea (near-solution)
Rotate in-place using two steps:
- Transpose the matrix (swap
matrix[i][j]withmatrix[j][i]). - Reverse each row.
This is equivalent to a 90-degree clockwise rotation.
Invariant: after transposing, rows become columns; reversing rows completes the rotation.
Algorithm (step-by-step)
- For each
iin[0..n-1]:- For each
jin[i+1..n-1], swapmatrix[i][j]andmatrix[j][i].
- For each
- For each row, reverse it in-place.
Correctness sketch
- Invariant: after transposing, rows become columns; reversing rows completes the rotation.
- Boundary/marker invariants ensure each cell is processed correctly.
- In-place encodings preserve original state until updates are finalized.
- Thus the final matrix matches the required transformation.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
After rotation:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Walk:
- transpose -> [[1,4,7],[2,5,8],[3,6,9]]
- reverse each row -> [[7,4,1],[8,5,2],[9,6,3]]
Pitfalls to avoid
- Transposing twice or reversing columns instead of rows.
- Using extra matrices (violates in-place requirement).
Complexity
- Time:
O(n^2) - Extra space:
O(1)
Implementation notes (Go)
- Transpose the matrix, then reverse each row in place.
- Only swap cells where
c > rto avoid double-swaps.
Run tests to see results
No issues detected