📌 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
Cyclic Shifts of a Matrix Problem
More Relevant Posts
-
🚀 Day 8/100 — #100DaysOfLeetCode Another day, another concept unlocked 💻🔥 ✅ Problem Solved: 🔹 LeetCode 73 — Set Matrix Zeroes 💡 Problem Idea: If any element in a matrix is 0, its entire row and column must be converted to 0 — and the challenge is to do this in-place without using extra space. 🧠 Algorithm & Tricks Learned: Instead of using extra arrays, we can use the first row and first column as markers. First pass → mark rows and columns that should become zero. Second pass → update the matrix based on those markers. Carefully handle the first row and first column separately to avoid losing information. ⚡ Key Insight: The matrix itself can act as storage, reducing extra memory usage. 📊 Complexity Analysis: Time Complexity: O(m × n) → traverse matrix twice Space Complexity: O(1) → solved in-place without extra data structures This problem taught me how small optimizations can significantly improve space efficiency. Learning to think beyond brute force every day 🚀 #100DaysOfLeetCode #LeetCode #DSA #MatrixProblems #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
Day 79/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Flatten Binary Tree to Linked List A powerful tree transformation problem using pointer manipulation. Problem idea: Convert a binary tree into a linked list in-place following preorder traversal. Key idea: Iterative traversal + rewiring (similar to Morris traversal idea). Why? • We need preorder sequence (Root → Left → Right) • Instead of extra space, we modify pointers in-place • Efficient and avoids recursion stack How it works: • Traverse using a pointer curr • If left child exists: → Find rightmost node of left subtree → Connect it to current’s right subtree → Move left subtree to right → Set left = null • Move to next node (curr.right) Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Tree problems can often be optimized using in-place pointer rewiring, avoiding extra space. 🔥 This pattern is very useful for tree flattening and traversal optimizations. Day 79 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinaryTree #MorrisTraversal #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
🚀 Just solved the Contains Duplicate problem with a fresh perspective! Instead of going with the traditional sorting + two pointer approach, I used the property of Set (uniqueness) to achieve an O(n) time complexity solution. 💡 Approach: - Traverse the array once - Use a HashSet to track elements - If an element already exists → duplicate found ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 🔁 On the other hand, the sorting + two pointer approach gives: - Time: O(n log n) - Space: O(1) 👉 So it’s a classic trade-off: - Optimize time → use Set - Optimize space → use Sorting+two pointer Really enjoyed breaking down this problem and comparing approaches — small problems like this build strong intuition for bigger ones 💪 #DataStructures #Algorithms #LeetCode #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Worked on a challenging problem: “Subarrays with K Different Integers” Key takeaway: Instead of directly solving for exactly K distinct elements, I learned a smarter approach: 👉 count(at most K) − count(at most K−1) 🔹 Concepts I practiced: Sliding Window technique HashMap for frequency tracking Two-pointer approach 🔹 What stood out: The idea of counting all valid subarrays ending at each index using (r - l + 1) was really powerful. It completely changed how I think about subarray problems. Always learning, one problem at a time. #DataStructures #Algorithms #Java #LeetCode #SlidingWindow #LearningJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 75 — Slow & Fast Pointer (Happy Number Detection) Extending the slow‑fast pointer pattern beyond linked lists — today I applied it to a mathematical problem involving cycles. 📌 Problem Solved: - LeetCode 202 – Happy Number 🧠 Key Learnings: 1️⃣ The Problem in a Nutshell A number is happy if repeatedly replacing it with the sum of squares of its digits eventually reaches 1. If it enters a cycle that doesn’t include 1, it’s unhappy. 2️⃣ Why Slow‑Fast Pointer Works - The sequence of numbers (n → sum of squares of digits → ...) will eventually either reach 1 or enter a cycle. - This is exactly like detecting a cycle in a linked list — except the “next” is defined mathematically. - Slow moves one step: `slow = sq(slow)` - Fast moves two steps: `fast = sq(sq(fast))` - If they meet at a value other than 1 → cycle exists → unhappy number. - If fast reaches 1 → happy number. 3️⃣ The sq() Helper Computes sum of squares of digits. Clean and reusable. 4️⃣ Edge Cases - n = 1 → returns true immediately (loop condition `fast != 1` fails, returns true). - Numbers like 2, 3, 4 eventually cycle (4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4). 💡 Takeaway: The slow‑fast pointer pattern isn’t just for linked lists — it’s a general cycle detection tool that works for any sequence with a deterministic “next” step. Recognizing this abstraction is what makes a great problem solver. No guilt about past breaks — just one problem at a time, one pattern at a time. #DSA #SlowFastPointer #HappyNumber #CycleDetection #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Day 6 of #100DaysOfLeetCode ✅ Today I solved LeetCode 128 — Longest Consecutive Sequence. 🧩 Problem Summary: Given an unsorted array of integers, the task is to find the length of the longest sequence of consecutive numbers. The challenge is to solve it in O(n) time complexity, which means sorting is not allowed. 💡 Key Learning: Instead of sorting, I used a HashSet for O(1) lookup. The main intuition: 👉 A number starts a sequence only if (num - 1) does NOT exist in the set. Then we expand forward (num + 1) to count the sequence length. ⚡ Concepts Practiced: • HashSet / Hashing • Optimized Searching (O(1) lookup) • Sequence Detection Pattern • Time Complexity Optimization 📈 Time Complexity: O(n) 📦 Space Complexity: O(n) Every day improving problem-solving skills and understanding data structures deeper 🚀 #DSA #LeetCode #Java #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 63 of #100DaysOfLeetCode ✅ Problem Solved: Unique Binary Search Trees (LeetCode 96) Today’s problem was a great example of how Dynamic Programming and mathematical patterns (Catalan Numbers) come together. 🔍 Key Insight: For every node chosen as root, the number of unique BSTs is: 👉 Left Subtrees × Right Subtrees This leads to the recurrence: dp[n] = Σ (dp[left] × dp[right]) 💡 What I learned: Breaking problems into smaller subproblems makes complex structures easier Recognizing patterns like Catalan Numbers is a game changer DP is not just about arrays, it's about thinking smart ⚡ Result: ✔️ Runtime: 0 ms (Beats 100%) ✔️ Clean and optimized solution Consistency is slowly turning into confidence 💪 #LeetCode #DataStructures #DynamicProgramming #CodingJourney #ProblemSolving #Java #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development