Matrix Similarity After Cyclic Shifts

Problem LinkSolution Link

Intuition #

Even rows are shifted right by k, and odd rows are shifted left by k. At first glance, these seem like two different checks. However, the condition for a row to be unchanged after a right shift by k is mathematically equivalent to being unchanged after a left shift by k — both reduce to:

row[j]==row[(j+k)modn]row[j] == row[(j + k) \mod n]

So we can apply a single uniform check across all rows without distinguishing even from odd.

Approach #

Complexity #

Code #

 1func areSimilar(mat [][]int, k int) bool {
 2	MOD := len(mat[0])
 3	k %= MOD
 4	for y, row := range mat {
 5		for x := range row {
 6			if mat[y][(x+k)%MOD] != mat[y][x] {
 7				return false
 8			}
 9		}
10	}
11
12	return true
13}