Leetcode 2946: Matrix Similarity After Cyclic Shifts

grid47
grid47
Exploring patterns and algorithms
Jan 17, 2024 5 min read

You are given an m x n matrix ‘mat’ and an integer ‘k’. The rows of the matrix undergo cyclic shifts: even-indexed rows shift left, and odd-indexed rows shift right. After performing these k shifts, determine if the matrix is identical to its original form.
Problem
Approach
Steps
Complexity
Input: You are given a 2D matrix 'mat' and an integer 'k', where 'mat[i][j]' represents the element in the ith row and jth column.
Example: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4
Constraints:
• 1 <= mat.length <= 25
• 1 <= mat[i].length <= 25
• 1 <= mat[i][j] <= 25
• 1 <= k <= 50
Output: Return true if the matrix is identical to its original after k shifts, otherwise return false.
Example: For mat = [[1,2,3],[4,5,6],[7,8,9]] and k = 4, the output is false.
Constraints:
Goal: The goal is to determine whether, after k cyclic shifts on the matrix, the matrix will match its original configuration.
Steps:
• For each row in the matrix, determine whether performing cyclic shifts k times results in the same row.
• For even-indexed rows, perform a left cyclic shift; for odd-indexed rows, perform a right cyclic shift.
Goal: The matrix can have up to 25 rows and 25 columns, and k can be at most 50.
Steps:
• mat.length <= 25
• mat[i].length <= 25
• mat[i][j] <= 25
• k <= 50
Assumptions:
• Matrix rows can have different lengths but will be bounded by the constraints.
• Cyclic shifts are defined as moving elements in a row from one end to the other, wrapping around.
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4
Explanation: After performing 4 shifts, the matrix is no longer identical to the original one, so the result is false.

Input: mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2
Explanation: After performing 2 shifts, the matrix becomes identical to its original form, so the result is true.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus