Matrix Similarity After Cyclic Shifts LeetCode Challenge

LeetCode Daily Challenge – Matrix Similarity After Cyclic Shifts Today I solved an interesting problem that involves matrix traversal + cyclic shifts logic. Problem Insight: We are given a matrix and an integer k. Even-indexed rows → shift left Odd-indexed rows → shift right We need to check if the matrix remains similar after k cyclic shifts. Key Idea: Instead of actually shifting the rows (which is costly), we calculate the expected index directly using modulo arithmetic. Why? Because shifting k times is equivalent to shifting k % n times (where n = number of columns). Logic Breakdown: For each element mat[i][j]: If row is even (i % 2 == 0) ➝ Left shift → new index = (j + k) % n If row is odd (i % 2 != 0) ➝ Right shift → new index = (j - k + n) % n Then simply compare: If all elements match expected positions → return true Otherwise → return false Why this approach? Avoids extra space No actual shifting needed Efficient → O(m × n) time complexity What I learned: Modulo is powerful for cyclic problems Always try to avoid simulation when math can solve it Pattern-based thinking helps in matrices Would love to hear if you solved it differently! #LeetCode #DataStructures #Java #CodingJourney #100DaysOfCode #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories