Rotate Image in Python

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        # Assuming a square matrix, so the length of the matrix gives us n.
        n = len(matrix)

        # Step 1: Transpose the matrix
        for i in range(n):
            # Start from `i` to avoid re-swapping previously swapped elements.
            for j in range(i, n):
                # Swap element at position (i, j) with element at position (j, i)
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

        # Step 2: Reverse each row
        for i in range(n):
            matrix[i].reverse()  # Reverse the ith row

PrevNext