Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A square matrix has only four orientations under repeated quarter-turns. A clockwise rotation can be performed in place by reversing the row order and then transposing, avoiding a separate rotated matrix.
Approach
Swap top and bottom rows, then swap entries across the main diagonal to complete one clockwise turn. Compare the result with target and repeat up to four times. The fourth turn returns to the original orientation, so the code still checks the zero-rotation case even though it rotates before comparing. Return true after any matching orientation, otherwise false. The reference approach mutates the input matrix during these checks.
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rotate(mat):
n = len(mat)
for i in range(n // 2):
for j in range(n):
mat[i][j], mat[n - 1 - i][j] = mat[n - 1 - i][j], mat[i][j]
for i in range(n):
for j in range(i + 1):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
return mat == target
for i in range(4):
if rotate(mat):
return True
return FalseComplexity analysis
Let n be the matrix dimension. Both displayed implementations perform at most four in-place rotations and comparisons, taking O(n^2) time and O(1) auxiliary space.
