SDE & MLE Prep

48. Rotate Image

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()