2946. Matrix Similarity After Cyclic Shifts
Description
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:
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
Solutions
Solution 1: Simulation
Thinking
Odd rows shift right by \(k\) and even rows left by \(k\); the matrix must stay unchanged. \(k\) may be reduced modulo the width, but comparing the cell that would land on \((i,j)\) avoids rotating.
On odd rows inspect \(mat[i][(j+k)\bmod n]\), on even rows \(mat[i][(j-k+n)\bmod n]\). One mismatch rejects. The matrix is at most \(25 \times 25\).
We iterate over each element of the matrix and check whether its position after the cyclic shift is the same as the element at the original position.
For odd-indexed rows, we shift elements to the right by \(k\) positions, so element \((i, j)\) moves to position \((i, (j + k) \bmod n)\) after the cyclic shift, where \(n\) is the number of columns.
For even-indexed rows, we shift elements to the left by \(k\) positions, so element \((i, j)\) moves to position \((i, (j - k + n) \bmod n)\) after the cyclic shift.
If at any point during the traversal we find that an element's position after the cyclic shift differs from the original, we return \(\text{false}\). If all elements remain the same after the full traversal, we return \(\text{true}\).
The time complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns of the matrix, respectively. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |



