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 Cyclic Shifts INPUT Original Matrix (mat): 1 2 3 4 Row 0 Row 1 (Even) (Odd) Input Values: mat = [[1,2],[3,4]] k = 2 Shift Directions: Even: LEFT Odd: RIGHT ALGORITHM STEPS 1 Get dimensions m=2 rows, n=2 cols 2 Calculate effective k k_eff = k % n = 2 % 2 = 0 3 Check condition If k_eff == 0, matrix returns to original 4 Return result 0 == 0 is TRUE Simulation (k=2): After k=1: 2 1 4 3 After k=2: 1 2 3 4 FINAL RESULT Comparison: Original 1 2 3 4 = Final 1 2 3 4 Output: true Matrices are IDENTICAL! OK Time: O(1) Space: O(1) Key Insight: After n cyclic shifts (where n = number of columns), any row returns to its original state. So we only need to check if k % n == 0. If true, matrix is identical to original. This gives us O(1) time complexity - no actual shifting needed! TutorialsPoint - Matrix Similarity After Cyclic Shifts | Optimal Solution
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