Determine Whether Matrix Can Be Obtained By Rotation - Problem

Imagine you have two n × n binary matrices (containing only 0s and 1s) - one called mat and another called target. Your task is to determine whether you can transform mat into target by rotating it in 90-degree increments (clockwise).

Think of it like rotating a game board or a puzzle piece - you can rotate it 0°, 90°, 180°, or 270° to see if any of these rotations match your target pattern.

Goal: Return true if any rotation of mat equals target, otherwise return false.

Example: If mat = [[0,1],[1,0]] and target = [[1,0],[0,1]], rotating mat by 90° clockwise gives us exactly the target!

Input & Output

example_1.py — Basic Rotation Match
$ Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
💡 Note: Rotating mat 90° clockwise transforms [0,1],[1,0] to [1,0],[0,1] which exactly matches target
example_2.py — No Possible Rotation
$ Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
💡 Note: No rotation of mat can produce target. Mat has three 1s, but target has only two 1s
example_3.py — Identity Matrix
$ Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
Output: true
💡 Note: Rotating mat 180° gives us the target matrix

Constraints

  • n == mat.length == mat[i].length == target.length == target[i].length
  • 1 ≤ n ≤ 20
  • mat[i][j] and target[i][j] are either 0 or 1
  • Note: Only 90-degree clockwise rotations are allowed

Visualization

Tap to expand
Matrix Rotation VisualizationOriginal Matrix01010101090° ClockwiseTarget Matrix✓ Rotation Formula: (i,j) → (j, n-1-i)Check each rotation without storing intermediate matrices
Understanding the Visualization
1
Identify Pattern
Recognize that we only need to check 4 possible orientations
2
Mathematical Mapping
Use formulas to map original positions to rotated positions
3
Direct Comparison
Compare elements directly without creating new matrices
4
Early Exit
Return true immediately when a match is found
Key Takeaway
🎯 Key Insight: We can check all 4 rotations mathematically in O(1) space by mapping coordinates directly, making this an elegant and efficient solution.
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
47.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen