Matrix Similarity After Cyclic Shifts - Problem
You are given an m x n integer matrix mat and an integer k. Your task is to determine if the matrix returns to its original state after performing k cyclic shift operations.
Here's how the shifting works:
- Even-indexed rows (0, 2, 4, ...) are cyclically shifted to the left
- Odd-indexed rows (1, 3, 5, ...) are cyclically shifted to the right
A cyclic shift means elements wrap around - when shifting left, the leftmost element moves to the rightmost position, and vice versa for right shifts.
Return true if the matrix is identical to the original after exactly k operations, false otherwise.
Example: If we have matrix [[1,2,3],[4,5,6]] with k=1:
- Row 0 (even): [1,2,3] → [2,3,1] (left shift)
- Row 1 (odd): [4,5,6] → [6,4,5] (right shift)
- Result: [[2,3,1],[6,4,5]] ≠ original, so return
false
Input & Output
example_1.py — Basic Example
$
Input:
mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2
›
Output:
true
💡 Note:
Each row has width 4. After k=2 shifts: Row 0 (even): [1,2,1,2] → [1,2,1,2] (2 left shifts), Row 1 (odd): [5,5,5,5] → [5,5,5,5] (identical elements), Row 2 (even): [6,3,6,3] → [6,3,6,3] (2 left shifts). Since k % 4 ≠ 0, but the pattern repeats due to identical elements, we get the original matrix.
example_2.py — Simple False Case
$
Input:
mat = [[2,2],[2,2]], k = 3
›
Output:
true
💡 Note:
All elements are identical, so no matter how many shifts we perform, the matrix remains the same. k % 2 = 1, but since all elements are equal, the matrix still returns to original state.
example_3.py — Different Widths
$
Input:
mat = [[1,2,3],[4,5,6]], k = 1
›
Output:
false
💡 Note:
Row 0 has width 3, after 1 left shift: [1,2,3] → [2,3,1]. Row 1 has width 3, after 1 right shift: [4,5,6] → [6,4,5]. Since k % 3 = 1 ≠ 0, the matrix doesn't return to original state.
Constraints
- 1 ≤ m, n ≤ 25
- 1 ≤ mat[i][j] ≤ 99
- 1 ≤ k ≤ 109
- All rows in the matrix have the same width
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
All items are in their starting positions on the belts
2
Start Rotation
Even belts rotate left, odd belts rotate right
3
Track Cycles
Each belt completes a full cycle after 'width' rotations
4
Check Alignment
All items return to start if k is multiple of each belt's width
Key Takeaway
🎯 Key Insight: Instead of simulating k shifts, we use the mathematical property that each row cycles back to its original state every n shifts (where n is the row width). We only need to check if k % n == 0 for all rows!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code