Solving Leetcode Interviews in Seconds with AI: Matrix Similarity After Cyclic Shifts
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2946" 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
You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed. The following proccess happens k times: Even-indexed rows (0, 2, 4, ...) are cyclically shifted to the left. Odd-indexed rows (1, 3, 5, ...) are cyclically shifted to the right. Return true if the final modified matrix after k steps is identical to the original matrix, and false otherwise. Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4 Output: false Explanation: In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index). Example 2: Input: mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2 Output: true Explanation: Example 3: Input: mat = [[2,2],[2,2]], k = 3 Output: true Explanation: As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same. Constraints: 1 <= mat.length <= 25 1 <= mat[i].length <= 25 1 <= mat[i][j] <= 25 1 <= k <= 50
Explanation
Here's the solution approach:
- Simulate the shifts: Directly simulate the left and right cyclic shifts on the rows of the matrix for the given number of steps
k. - Compare with original: After performing all the shifts, compare the modified matrix with the original matrix element by element.
Return the result: Return
Trueif the matrices are identical, andFalseotherwise.Runtime Complexity: O(m*n*k), where m is the number of rows, n is the number of columns, and k is the number of steps. Storage Complexity: O(m*n) to create a copy of the matrix.
Code
def areSimilar(mat, k):
m = len(mat)
n = len(mat[0])
shifted_mat = [row[:] for row in mat] # Create a copy
for _ in range(k):
for i in range(m):
if i % 2 == 0: # Even row: left shift
temp = shifted_mat[i][0]
for j in range(n - 1):
shifted_mat[i][j] = shifted_mat[i][j + 1]
shifted_mat[i][n - 1] = temp
else: # Odd row: right shift
temp = shifted_mat[i][n - 1]
for j in range(n - 1, 0, -1):
shifted_mat[i][j] = shifted_mat[i][j - 1]
shifted_mat[i][0] = temp
for i in range(m):
for j in range(n):
if shifted_mat[i][j] != mat[i][j]:
return False
return True