Cyclic Shifts of a Matrix Problem

📌 LeetCode Daily Challenge — Day 27 Problem: 3786. Cyclic Shifts of a Matrix Topic: Array, Matrix, Math, Simulation   📌 Quick Problem Sense: You're given an m × n matrix and an integer k. Every step: even-indexed rows shift left, odd-indexed rows shift right — repeated k times. Return true if the matrix after k steps is identical to the original. The catch? k can be huge — so simulating step by step is a dead end. 🚫   🧠 Approach (Simple Thinking): 🔹 A row of length n always returns to original after n shifts — but it might return sooner! 🔹 The minimum cyclic period of a row = the smallest divisor d of n such that the row is just a block of size d repeated 🔹 Check it: row[j] == row[j % d] for all j — if true, d is the period! 🔹 Direction (left vs right) doesn't affect the period — both complete their cycle in the same number of steps 🔹 The matrix restores to original iff k % period == 0 for every row 🔹 Get all divisors of n once in O(√n), check each row against them — no simulation needed! 🎯   ⏱️ Time Complexity: Divisors of n → O(√n) Per row period check → O(d(n) × n) All rows → O(m × d(n) × n) Blazing fast — no k-step simulation ever needed!   📦 Space Complexity: Just a divisors list → O(√n) Zero extra matrix copies or simulation buffers!   I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/gbqN_Y7a If you solved it using the KMP failure function to find the string period in O(n), I'd love to see that approach, drop it in the comments 💬 See you in the next problem 👋 #LeetCode #DSA #CodingChallenge #Java #ProblemSolving

  • graphical user interface, text, application, email

To view or add a comment, sign in

Explore content categories