Day 78: Balancing X and Y (The Grid Grind) ⚖️ Problem 3212: Count Submatrices With Equal Frequency of X and Y Yesterday’s logic was so good I had to run it back. The mission: count all submatrices starting from (0,0) that have at least one 'X' and an equal number of 'X's and 'Y's. The Strategy: • Net Balance Trick: Assigned 'X' as 1 and 'Y' as -1. If the prefix sum of a submatrix is 0, the frequencies are equal. Simple math, big brain energy. 🧠 • 2D Prefix Sums: Used the inclusion-exclusion principle to keep the count updated in a single pass. • The "At Least One X" Check: Maintained a separate prefix matrix just to track if an 'X' had even shown up yet. No 'X', no entry. It might not be the most "optimized" code in the world yet, but it passes the tests and the logic is solid. In a world of complex algorithms, sometimes the O(M⋅N) "it just works" approach is the real MVP. 🚀 #LeetCode #Java #DataStructures #Algorithms #DailyCode
Balancing X and Y in Submatrices with Equal Frequency
More Relevant Posts
-
🚀 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 99: Square Root Decomposition & Prefix Multiplications ⚡ Problem 3655: XOR After Range Multiplication Queries II Yesterday’s brute force approach hit a wall today with a TLE (Time Limit Exceeded). The constraints were significantly tighter, requiring a more sophisticated optimization. The Strategy: Square Root Decomposition To handle the queries efficiently, I split the problem based on the step size k: • Large Steps (k ≥ √N): For large gaps, the number of updates is small enough that direct simulation still works within time limits. • Small Steps (k < √N): This is where the magic happens. For small k, I used a Difference Array technique modified for multiplications. • Modular Inverse & Prefix Products: Instead of updating every index, I marked the start (L) and end (R) of the range. I used modInverse to "cancel out" the multiplication after the range ended. A final prefix product pass (jumping by k) applied all updates in O(N) time. Technical Highlights: • Fermat's Little Theorem: Used modPow(x, MOD - 2) to calculate the modular inverse for division. • Complexity: Reduced the worst-case runtime from O(Q⋅N) to O((Q+N)√N). One day away from 100, but the focus remains on the problem in front of me. Consistency isn't about the destination; it's about the quality of the journey. 🚀 #LeetCode #Java #Algorithms #DataStructures #SquareRootDecomposition #DailyCode
To view or add a comment, sign in
-
-
Today I solved the classic Rotate Array problem — a simple-looking question that teaches a powerful concept: in-place transformation. 💡 Problem: Rotate an array to the right by k steps without using extra space. 🧠 Approach (Optimal): Instead of shifting elements one by one (O(n·k)), I used a smarter trick: ✔️ Reverse the entire array ✔️ Reverse first k elements ✔️ Reverse remaining elements ⚡ This reduces complexity to: ⏱️ Time → O(n) 📦 Space → O(1) 🔥 Key Learning: Sometimes, reversing parts of a data structure can simplify what looks like a complex movement problem. 📌 Problems like this strengthen understanding of: • Two-pointer technique • In-place algorithms • Array manipulation Consistency is key — one problem at a time! 💪 #DataStructures #Algorithms #Java #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 𝐒𝐨𝐥𝐯𝐞𝐝 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: Count Submatrices With Equal Frequency of X and Y (Medium) Today’s problem looked simple at first glance, but had a subtle twist, we needed to count submatrices that: ✔️ 𝐈𝐧𝐜𝐥𝐮𝐝𝐞 𝐭𝐡𝐞 𝐭𝐨𝐩-𝐥𝐞𝐟𝐭 𝐜𝐞𝐥𝐥 (𝟎,𝟎) ✔️ 𝐇𝐚𝐯𝐞 𝐞𝐪𝐮𝐚𝐥 𝐧𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 '𝐗' 𝐚𝐧𝐝 '𝐘' ✔️ 𝐂𝐨𝐧𝐭𝐚𝐢𝐧 𝐚𝐭 𝐥𝐞𝐚𝐬𝐭 𝐨𝐧𝐞 '𝐗' 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: Instead of checking every possible submatrix (which would be too slow), we can use 𝟐𝐃 𝐩𝐫𝐞𝐟𝐢𝐱 𝐬𝐮𝐦𝐬 to efficiently track counts of 'X' and 'Y'. 🔹 𝐁𝐮𝐢𝐥𝐝 𝐭𝐰𝐨 𝐩𝐫𝐞𝐟𝐢𝐱 𝐦𝐚𝐭𝐫𝐢𝐜𝐞𝐬: px[i][j] → count of 'X' from (0,0) to (i,j) py[i][j] → count of 'Y' from (0,0) to (i,j) 🔹 𝐓𝐡𝐞𝐧 𝐟𝐨𝐫 𝐞𝐚𝐜𝐡 𝐜𝐞𝐥𝐥 (𝐢,𝐣): If px[i][j] == py[i][j] and px[i][j] > 0, we found a valid submatrix! 𝐖𝐡𝐲 𝐭𝐡𝐢𝐬 𝐰𝐨𝐫𝐤𝐬: Every (i,j) represents a submatrix from (0,0) → (i,j). Prefix sums let us compute counts in O(1) per cell → overall O(m × n). 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: Time: O(m × n) Space: O(m × n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲: Prefix sums are incredibly powerful for grid problems especially when dealing with frequency/count constraints. Another day, another problem solved. Let’s keep building momentum! #LeetCode #DailyCoding #DataStructures #Algorithms #Java #ProblemSolving #CodingJourney
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 85: Leveling Up on Grid Partitions 🧩 Problem 3548: Equal Sum Grid Partition II Today was a grind, but a rewarding one. I tackled the "Hard" version of yesterday’s partition problem. This time, a simple cut wasn't enough—I had to determine if removing exactly one element could balance the two resulting halves. The Strategy: • Frequency Tracking: Standard sums weren't enough. I implemented frequency arrays to track exactly which values existed in each partition. This allowed for O(1) lookups to see if a "balancing" value was available. • The "Diff" Logic: At every potential cut (horizontal or vertical), I calculated the difference between the two halves. ∘ If diff > 0, I searched the "heavy" side for a value equal to the difference to remove. ∘ If diff < 0, I searched the "light" side (which is technically heavier in total weight) for the absolute difference. • Constraint Management: Handled strict boundary rules to ensure that removing an element wouldn't leave a partition disconnected. Solving a Hard-tagged problem after a long debugging session is the best kind of "aha!" moment. It’s a reminder that consistency pays off—yesterday's "Medium" was the foundation for today's breakthrough. 🚀 #LeetCode #Java #Algorithms #DataStructures #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
💭 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 105: Circular Arrays & Shortest Paths 🔄 Problem 2515: Shortest Distance to Target String in a Circular Array Today’s challenge involved finding the minimum steps to reach a target string in a circular array, allowing movement in both directions. The Strategy: • Bidirectional Search: Since the array is circular, the distance can be calculated in two ways: moving forward or moving backward. • Modular Arithmetic: I used (dist + n) % n to handle the wrap-around logic seamlessly, ensuring the index stays within bounds regardless of the direction. • Optimization: By iterating once through the array and comparing the distances for every occurrence of the target, I maintained an O(N) time complexity. Sometimes the most elegant way to handle a "circular" problem is simply embracing the symmetry of the path. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
🔥 Day 352 – Daily DSA Challenge! 🔥 Problem: 📦 Subarray Product Less Than K Given an array nums and an integer k, return the number of contiguous subarrays where the product of all elements is strictly less than k. 💡 Key Insight — Sliding Window (Two Pointers) Brute force would check all subarrays → O(n²) ❌ Instead, we use a sliding window to maintain a valid product. Core idea: 🧠 How It Works 🔹 Expand the window by moving right 🔹 Multiply current element into prod 🔹 If product ≥ k → shrink window from left 🔹 Once valid, all subarrays ending at right are valid 👉 Count added: right - left + 1 ⚡ Optimized Plan ✅ Initialize: left = 0, prod = 1, count = 0 ✅ For each right: Multiply nums[right] While product ≥ k: divide by nums[left] move left Add (right - left + 1) to count ⚙️ Complexity ✅ Time Complexity: O(n) (each element enters and exits window once) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why does this approach fail if negative numbers are allowed? 2️⃣ How would you modify this for sum < k instead of product? 3️⃣ Can you solve this using log transformation + prefix sum? #DSA #Day352 #LeetCode #SlidingWindow #TwoPointers #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
The High Cost of the Wrong Initial Choice I have seen complex computation logic for over a million records take hours to run simply because of inefficient, row-by-row processing that is offered by database stored procedures and traditional java/python code. It is slow, impossible to scale, and eventually kills your product's edge in the market. By moving to vectorized logic with tools like NumPy or Polars, you can turn those hours of computation into milliseconds. This is not just about using newer tools, it is about leveraging modern execution like #SIMD (Single Instruction Multiple Data) and #multithreading to gain a massive competitive advantage. If your backend is computation heavy and you're still stuck in legacy loops, you are leaving performance, market edge and money on the table. References: https://lnkd.in/g8j3A5Bn https://lnkd.in/gaPnFUQm https://lnkd.in/gWt9WHnp #DataEngineering #SystemDesign #NumPy #PerformanceOptimization #Scalability #PythonProgramming #TechStrategy #Vectorization #TechToolChoice
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