Solving Leetcode Interviews in Seconds with AI: Determine Whether Matrix Can Be Obtained By Rotation
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1886" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] Output: true Explanation: We can rotate mat 90 degrees clockwise to make mat equal target. Example 2: Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]] Output: false Explanation: It is impossible to make mat equal to target by rotating mat. Example 3: Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]] Output: true Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target. Constraints: n == mat.length == target.length n == mat[i].length == target[i].length 1 <= n <= 10 mat[i][j] and target[i][j] are either 0 or 1.
Explanation
Here's an efficient solution to determine if a binary matrix can be transformed into a target matrix through 90-degree rotations:
- Rotation and Comparison: The core idea is to rotate the original matrix
matby 90 degrees clockwise up to three times and compare it with thetargetmatrix after each rotation. - Early Exit: If a rotation results in the
matbecoming equal to thetarget, we immediately returnTrue. Final Check: If none of the rotations result in a match, it implies that the transformation is impossible, and we return
False.Runtime Complexity: O(n2), where n is the dimension of the matrix.
- Storage Complexity: O(1) - We are doing the rotation in-place, hence constant storage.
Code
def findRotation(mat, target):
"""
Checks if mat can be transformed into target by 90-degree rotations.
Args:
mat: The source binary matrix.
target: The target binary matrix.
Returns:
True if a transformation is possible, False otherwise.
"""
def rotate(matrix):
"""Rotates a matrix 90 degrees clockwise in-place."""
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = matrix[i][j]
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = temp
def are_equal(mat1, mat2):
"""Checks if two matrices are equal."""
n = len(mat1)
for i in range(n):
for j in range(n):
if mat1[i][j] != mat2[i][j]:
return False
return True
for _ in range(4):
if are_equal(mat, target):
return True
rotate(mat) # Rotate mat in-place
return False