Matrix Similarity After Cyclic Shifts - Problem

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.

Input & Output

Example 1 — Basic 2x2 Matrix
$ Input: mat = [[1,2],[3,4]], k = 2
Output: true
💡 Note: After 1 shift: row 0 becomes [2,1], row 1 becomes [4,3]. After 2 shifts: row 0 becomes [1,2], row 1 becomes [3,4]. Matrix returns to original.
Example 2 — Single Shift
$ Input: mat = [[2,1],[3,4]], k = 1
Output: false
💡 Note: After 1 shift: row 0 becomes [1,2], row 1 becomes [4,3]. This is different from original [[2,1],[3,4]].
Example 3 — Large k Value
$ Input: mat = [[1,2,1,2]], k = 4
Output: true
💡 Note: Row has period 2 (repeats every 2 elements). After k=4 shifts, 4 % 2 = 0, so it returns to original.

Constraints

  • 1 ≤ m, n ≤ 25
  • 1 ≤ mat[i][j] ≤ 99
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Matrix Similarity After Cyclic ShiftsOriginal Matrix123456Row 0 (even)Row 1 (odd)k shiftsShifting ProcessEven rows: ← shift leftOdd rows: shift right →Repeat k timescompareResult Matrix??????Question: Does the result matrix equal the original?Return trueif matrices matchTime: O(k×m×n) simulation vs O(m×n) mathematical
Understanding the Visualization
1
Input
Matrix with even/odd rows and shift count k
2
Process
Even rows shift left, odd rows shift right
3
Output
Check if matrix returns to original
Key Takeaway
🎯 Key Insight: Use mathematical periods instead of simulation to efficiently determine if matrix returns to original state
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
542 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen