# Rotate Image https://leetcode.com/problems/rotate-image/ ## Solution 1: Rotate Groups of Four Cells ```python n = len(matrix) for i in range(n // 2 + n % 2): for j in range(i, n - i - 1): ( matrix[i][j], matrix[j][-(i + 1)], matrix[-(i + 1)][-(j + 1)], matrix[-(j + 1)][i], ) = ( matrix[-(j + 1)][i], matrix[i][j], matrix[j][-(i + 1)], matrix[-(i + 1)][-(j + 1)], ) ``` The key lies in carefully examine the range for `i` and `j`! Draw matrices of different sizes and experiment with the indices. Complexity = $O(n^2)$ as each cell is processed once. ## Solution 2: Transpose and Reflect ```python def transpose(matrix): n = len(matrix) for i in range(n): for j in range(i + 1, n): matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i] def reflect(matrix): n = len(matrix) for i in range(n): for j in range(n // 2): ( matrix[i][j], matrix[i][-j - 1] ) = ( matrix[i][-j - 1], matrix[i][j], ) def rotate(matrix): transpose(matrix) reflect(matrix) ``` Same complexity but twice as many read/write access.