Determine Whether Matrix Can Be Obtained By Rotation - Problem

Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.

A 90-degree rotation means rotating the matrix clockwise by 90 degrees. You can perform this rotation 0, 1, 2, or 3 times to check if any of the resulting matrices match the target.

Input & Output

Example 1 — Basic Rotation Match
$ Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
💡 Note: Rotating mat 90° clockwise gives [[1,0],[0,1]] which equals target. The top-left 0 moves to top-right, top-right 1 moves to bottom-right, etc.
Example 2 — No Rotation Match
$ Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
💡 Note: None of the 4 rotations (0°, 90°, 180°, 270°) of mat equals target. mat has two 1s but target has them in different positions that can't be achieved by rotation.
Example 3 — 180° Rotation Match
$ 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 target. The bottom row [1,1,1] becomes the top row, and the top row [0,0,0] becomes the bottom row.

Constraints

  • n == mat.length == mat[i].length == target.length == target[i].length
  • 1 ≤ n ≤ 10
  • mat[i][j] and target[i][j] are either 0 or 1

Visualization

Tap to expand
Matrix Rotation Check INPUT mat: 0 1 1 0 target: 1 0 0 1 mat = [[0,1],[1,0]] target = [[1,0],[0,1]] ALGORITHM STEPS 1 Try 0 rotations Compare mat with target 2 Rotate 90 degrees In-place rotation check 0 1 1 0 --> 1 0 0 1 3 Compare matrices Check if equal to target 4 Match Found! After 1 rotation = target 90 deg Rotation Formula: new[j][n-1-i] = old[i][j] Try 0, 1, 2, or 3 rotations FINAL RESULT After 1 rotation of mat: 1 0 0 1 = target MATCH FOUND! OK - Equal after 1 rotation Output: true Rotation possible Key Insight: A matrix can only have 4 unique orientations: 0, 90, 180, and 270 degree rotations. Instead of actually rotating, we can use index mapping: rotated[j][n-1-i] = original[i][j]. Time: O(n^2) per comparison, Space: O(1) for in-place check or O(n^2) if creating rotated copies. TutorialsPoint - Determine Whether Matrix Can Be Obtained By Rotation | In-Place Rotation Check
Asked in
Facebook 15 Google 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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