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
Matrix Similarity After Cyclic Shifts LeetCode Challenge
More Relevant Posts
-
💭 Today’s lesson: Not every problem needs complex logic. Sometimes, it’s about seeing the pattern clearly. I was solving today’s LeetCode problem: 👉 Check if two strings can be made equal with operations At first glance, it felt like a typical string manipulation problem. But the constraint made it interesting: You can only swap characters at positions with the same parity (even ↔ even, odd ↔ odd). Initially, I started overthinking: ->“Do I need to simulate swaps?” ->“Is this a graph / permutation problem?” But then I paused and asked: 👉 What actually changes after unlimited valid operations? 💡 That’s when the key insight clicked: ->Characters at even indices can only rearrange among even positions ->Characters at odd indices can only rearrange among odd positions So instead of simulating swaps, we just need to check: ✔ Do both strings have the same frequency of characters at even positions? ✔ And the same for odd positions? That reduces the problem to a simple frequency comparison — much cleaner and efficient. Implemented it using two frequency arrays (even & odd), and it worked smoothly ✅ 🔍 Big takeaway: Before jumping into implementation, always ask: 👉 What constraints actually limit or define the problem? Sometimes, the best solution is not more code — but better observation. #DataStructures #Algorithms #LeetCode #ProblemSolving #Java #SoftwareEngineering #LearningJourney
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
-
📌 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
To view or add a comment, sign in
-
-
🚀 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 27 of my #30DayCodeChallenge: The Efficiency of Binary Exponentiation! The Problem: Pow(x, n). Implementing the power function to calculate x". While it sounds simple, the challenge lies in handling large exponents (up to 231 - 1) and negative powers without hitting time limits or overflow. The Logic: This problem is a classic example of Divide and Conquer optimized through Binary Exponentiation (also known as Exponentiation by Squaring): 1. Bitwise Breakdown: Instead of multiplying x by itself n times (O(n)), we decompose n into powers of 2. For example, x13 is x8. x4. x¹. This brings our complexity down to O(log n). 2. The Iterative Jump: In every iteration of the loop, we square the current base (x = x x). If the current bit of n is 1 (checked via n & 1), we multiply our result by the current base. 3. Handling the Edge Cases: * Negative Exponents: If n is negative, we calculate xI" and then take the reciprocal (1/result). Overflow: We use a long for n during calculation to avoid overflow when converting -2, 147, 483, 648 to a positive value. The Calculation: By halving the power at each step, we transform a task that could take 2 billion operations into one that takes just 31. One step closer to mastery. Onward to Day 28! #Java #Algorithms #DataStructures #BinaryExponentiation #ProblemSolving #150DaysOfCode #SoftwareEngineer
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode – Rotate Image Today I worked on an interesting matrix problem: Rotate Image (90° clockwise) 🔄 💡 Key Learning: Instead of using extra space, the challenge is to rotate the matrix in-place. 🧠 Approach I used: 1️⃣ Transpose the matrix (convert rows → columns) 2️⃣ Reverse each row This combination effectively rotates the matrix by 90° clockwise without using extra memory. 📌 Example: Input: [[1,2,3], [4,5,6], [7,8,9]] Output: [[7,4,1], [8,5,2], [9,6,3]] ⚡ Complexity: Time: O(n²) Space: O(1) (in-place) 💻 Implemented in Java and successfully passed all test cases ✅ This problem really helped me strengthen my understanding of matrix manipulation and in-place algorithms. #LeetCode #DataStructures #Java #CodingPractice #ProblemSolving #Algorithms #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 544 of #750DaysOfCode 🚀 🧩 Problem Solved: Matrix Similarity After Cyclic Shifts Today’s problem focused on understanding how cyclic shifts affect matrix rows and optimizing the approach instead of brute-force simulation. 🔍 Key Insight: Instead of performing the shift operation k times, we can reduce it using: 👉 k % n (where n = number of columns) This works because after n shifts, the row returns to its original form. 💡 Approach: Even-indexed rows → shift left Odd-indexed rows → shift right Compare each element with its expected position after shifting No need to actually modify the matrix ✅ ⚡ Optimization: Avoided unnecessary operations by directly checking positions using modulo arithmetic. 📊 Complexity: Time: O(m × n) Space: O(1) 🎯 What I Learned: Efficient problem solving is not about doing more operations, but about reducing them smartly. Recognizing patterns like cyclic repetition can drastically improve performance. 💬 Question for you: Have you ever optimized a brute-force solution using mathematical insights like modulo? #LeetCode #DataStructures #Algorithms #Java #CodingJourney #ProblemSolving #TechInterview #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
✳️Day 35 of #100DaysOfCode✳️ 📌 Cracking the "Redundant Connection" Problem with DSU! 🛠️ My Approach: The DSU Strategy The Disjoint Set Union (or Union-Find) algorithm is perfect here because it allows us to track connected components efficiently as we iterate through the edges. ✨The Steps in my Code: 1️⃣Initialization: Created a parent array where every node is initially its own parent (representing n independent sets). 2️⃣Iterative Union: For every edge (u, v) in the input: Find the root (representative) of u. Find the root (representative) of v. Cycle Detection: * If find(u) == find(v), it means u and v are already part of the same connected component. Adding this edge would create a cycle. 🚩 Since the problem asks for the last edge that causes the cycle, I return this edge immediately. 3️⃣Union: If they are in different sets, I perform a union by setting the parent of one root to the other. 4️⃣Optimization: I used Path Compression in the find function to keep the tree flat, ensuring almost constant time complexity. 💡 When should you use DSU? 🔅DSU is a powerhouse for specific graph scenarios. Reach for it when: Cycle Detection: You need to check if adding an edge creates a cycle in an undirected graph. 🔅Connected Components: You need to count or manage groups of connected nodes dynamically. 🔅Minimum Spanning Trees: It’s the backbone of Kruskal’s Algorithm. Grid Problems: Identifying "islands" or connected regions in a 2D matrix. #DataStructures #Algorithms #LeetCode #Java #GraphTheory #CodingLife #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 100 Days of Code Day-25 LeetCode Problem Solved: Reverse Nodes in k-Group I recently worked on a Linked List problem that focuses on reversing nodes in groups of size k while preserving the remaining structure if the group size is less than k. 🔹 Strengthened my understanding of pointer manipulation 🔹 Improved problem decomposition skills 🔹 Practiced recursive thinking for efficient implementation 💡 Key takeaway: Breaking complex problems into smaller, manageable parts significantly simplifies the solution approach. Continuing to build consistency in problem-solving and deepen my understanding of Data Structures & Algorithms. #LeetCode #DataStructures #Algorithms #Java #ProblemSolving #SoftwareDevelopment
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