48. Rotate Image
- Array
- Math
- Matrix
TIME
O(n²)
SPACE
O(1)
Intuition
A clockwise rotation moves each value from (row, col) to (col, n - 1 - row). Instead of creating another matrix, we can get the same final layout with two in-place operations:
- Transpose the matrix across the main diagonal.
- Reverse each row.
After transposing, rows become columns. Reversing each row then puts those columns in clockwise order.
Approach
- Let
nbe the matrix size. - Transpose the matrix:
- Swap
matrix[row][col]withmatrix[col][row]for everycol > row.
- Swap
- Reverse every row in-place.
Complexity
- Time: O(n²), each matrix cell is touched a constant number of times
- Space: O(1), only temporary variables are used
Edge Cases
n = 1→ the matrix remains unchanged- Negative values → values are only moved, not compared or computed
- Even and odd
n→ transpose and row reversal handle both
Code
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
48. Rotate Image
Time: O(n²)
Space: O(1)
"""
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()/**
* 48. Rotate Image
* Time: O(n²)
* Space: O(1)
*/
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int row = 0; row < n; row++) {
for (int col = row + 1; col < n; col++) {
int temp = matrix[row][col];
matrix[row][col] = matrix[col][row];
matrix[col][row] = temp;
}
}
for (int row = 0; row < n; row++) {
reverse(matrix[row]);
}
}
private void reverse(int[] row) {
int left = 0;
int right = row.length - 1;
while (left < right) {
int temp = row[left];
row[left] = row[right];
row[right] = temp;
left++;
right--;
}
}
}