Skip to content

2946. Matrix Similarity After Cyclic Shifts

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  bool areSimilar(vector<vector<int>>& mat, int k) {
    const int n = mat[0].size();
    for (const vector<int>& row : mat)
      for (int j = 0; j < n; ++j)
        if (row[j] != row[(j + k) % n])
          return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public boolean areSimilar(int[][] mat, int k) {
    final int n = mat[0].length;
    for (int[] row : mat)
      for (int j = 0; j < n; ++j)
        if (row[j] != row[(j + k) % n])
          return false;
    return true;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def areSimilar(self, mat: list[list[int]], k: int) -> bool:
    n = len(mat[0])
    for row in mat:
      for j in range(n):
        if row[j] != row[(j + k) % n]:
          return False
    return True