Skip to main content
Back to problems
#2946
Easy Algorithms

Matrix similarity after cyclic shifts

Array Math Matrix Simulation
59.4% acceptance
Feb 25, 2026
195
68
You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed. The following proccess 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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn are_similar(mat: Vec<Vec<i32>>, k: i32) -> bool {
    let cols = mat[0].len();
    let shift = (k as usize) % cols;
    if shift == 0 {
      return true;
    }
    for (row_idx, row) in mat.iter().enumerate() {
      for j in 0..cols {
        // Even rows shift left by shift: row[j] should equal row[(j+shift) % cols]
        // Odd rows shift right by shift: row[j] should equal row[(j + cols - shift) % cols]
        let src = if row_idx % 2 == 0 {
          (j + shift) % cols
        } else {
          (j + cols - shift) % cols
        };
        if row[j] != row[src] {
          return false;
        }
      }
    }
    true
  }
}