Leetcode: 48. Rotate Image

Problem Statement

Patterns

Prompts

Solution

Fix one element and derive the relative position of all other elements. Elements from the first row will come from the first column. Elements from the first column will come from elements from the last row. Elements from the last column will come from element from the last column. Time complexity is \(O(n ^ 2)\) and space is \(O(1)\).

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        N = len(matrix)
        for i in range(N // 2 + N % 2):
            for j in range(N // 2):
                (
                    matrix[i][j],
                    matrix[N - 1 - j][i],
                    matrix[N - 1 - i][N - 1 - j],
                    matrix[j][N - 1 - i],
                ) = (
                    matrix[N - 1 - j][i],
                    matrix[N - 1 - i][N - 1 - j],
                    matrix[j][N - 1 - i],
                    matrix[i][j],
                )