Matrix Similarity After Cyclic Shifts Problem
Description
LeetCode Problem 2946.
You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed.
The following process 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 <= 251 <= mat[i].length <= 251 <= mat[i][j] <= 251 <= k <= 50
Solution
Approach: Simulation
Shifting a row k times only matters modulo the row length n, so the matrix is unchanged exactly when every element equals the element that would land in its place.
For an odd-indexed row (shifted right), the element at column j comes from column (j - k) and ends at column (j + k) mod n, so it must equal mat[i][(j + k) mod n]. For an even-indexed row (shifted left), compare with mat[i][(j - k + n) mod n], after reducing k modulo n. If any element differs, return false; otherwise true.
Complexity: O(mn) time and O(1) extra space, where m and n are the number of rows and columns.
class Solution:
def areSimilar(self, mat: List[List[int]], k: int) -> bool:
n = len(mat[0])
for i, row in enumerate(mat):
for j, x in enumerate(row):
if i % 2 == 1 and x != mat[i][(j + k) % n]:
return False
if i % 2 == 0 and x != mat[i][(j - k + n) % n]:
return False
return True