Matrix Similarity After Cyclic Shifts — LeetCode 2946 Python Solution

EasyArrayMathMatrixSimulation
Problem
#2946
Reading time
2 min

The problem

You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed.

Python solution

Python
class Solution:
    def areSimilar(self, mat: List[List[int]], k: int) -> bool:
        n = len(mat[0])
        for i, row in enumerate(mat):
            for j, x in enumerate(row):
                if i % 2 == 1 and x != mat[i][(j + k) % n]:
                    return False
                if i % 2 == 0 and x != mat[i][(j - k + n) % n]:
                    return False
        return True

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2946. Matrix Similarity After Cyclic Shifts is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2946. Matrix Similarity After Cyclic Shifts?
LeetCode 2946. Matrix Similarity After Cyclic Shifts is rated Easy on LeetCode.
What topics does LeetCode 2946. Matrix Similarity After Cyclic Shifts cover?
LeetCode 2946. Matrix Similarity After Cyclic Shifts is tagged Array, Math, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview