#1886
Determine Whether Matrix Can Be Obtained By Rotation
EasyArrayMatrixMatrix ManipulationArray Rotation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
Instead of performing rotations, we can directly check if the target matrix can be obtained by comparing the matrices in their rotated forms using a helper function.
⚙️
Algorithm
3 steps- 1Step 1: Create a function to check if two matrices are equal.
- 2Step 2: Create a function to rotate the matrix 90 degrees clockwise.
- 3Step 3: Check the original matrix and its three rotated forms against the target matrix.
solution.py10 lines
1def rotate(mat):
2 n = len(mat)
3 return [[mat[n - j - 1][i] for j in range(n)] for i in range(n)]
4
5def canBeObtained(mat, target):
6 for _ in range(4):
7 if mat == target:
8 return True
9 mat = rotate(mat)
10 return Falseℹ
Complexity note: The time complexity remains O(n²) due to the same reasoning as the brute force approach, but we optimize by avoiding unnecessary checks after finding a match.
- 1The problem requires understanding matrix rotations, which can be visualized as rotating a physical object.
- 2Checking all four orientations of the matrix is essential to determine if the target can be achieved.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.