LeetCode Entry

2946. Matrix Similarity After Cyclic Shifts

27.03.2026 easy 2026 kotlin rust

Shift rows k times left and right

2946. Matrix Similarity After Cyclic Shifts easy substack youtube

27032026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1310

Problem TLDR

Shift rows k times left and right #easy #matrxi

Intuition

Brute force is accepted.

Approach

  • we can shift by k instead of by 1 k times
  • rows must be periodic or size == k, so left shift is the same as right shift
  • just check each row, don’t have to create a matrix

Complexity

  • Time complexity: \(O(nm)\)

  • Space complexity: \(O(1)\)

Code

// 15ms
    fun areSimilar(m: Array<IntArray>, k: Int) =
    m.all { r -> r.indices.all { r[it] == r[(it+k)%r.size] }}
// 0ms
    pub fn are_similar(m: Vec<Vec<i32>>, k: i32) -> bool {
        m.iter().all(|r| (0..r.len()).all(|i| r[i] == r[(i + k as usize) % r.len()]))
    }