48. Rotate Image
Asked at 32Bloomberg66Microsoft66Apple65Amazon63Google56Meta54Nvidia60ByteDance59tcs42SIG92Rakuten88Citigroup81Qualcomm76Mastercard75Zoho74Nutanix71Cisco70Roblox67Capital One66Samsung63Visa61IBM55Infosys54Tesla52Adobe44Accenture44Flipkart43Anduril41Oracle41Uber40TikTok35Goldman Sachs21
Problem
Rotate the n×n matrix 90° clockwise in place, without allocating another matrix.
Example: [[1,2,3],[4,5,6],[7,8,9]] → [[7,4,1],[8,5,2],[9,6,3]]
Transpose (swap m[i][j] with m[j][i]), then reverse every row. In place.
Complexity: O(n²) time, O(1) space.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; Solution().rotate(m)
assert m == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
m = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; Solution().rotate(m)
assert m == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
m = [[1]]; Solution().rotate(m)
assert m == [[1]]
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) { int t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; }
for (int[] row : matrix)
for (int l = 0, r = n - 1; l < r; l++, r--) { int t = row[l]; row[l] = row[r]; row[r] = t; }
}
}
func rotate(matrix [][]int) {
n := len(matrix)
for i := 0; i < n; i++ { // transpose...
for j := i + 1; j < n; j++ {
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
}
}
for _, row := range matrix { // ...then mirror each row
for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
row[l], row[r] = row[r], row[l]
}
}
}