🚀 Day 50 of DSA – Minimum Absolute Difference in Sliding Submatrix Solved a matrix problem where for every k x k submatrix, we need to find the minimum absolute difference between any two distinct values. 💡 Key Insight For each submatrix: collect all values keep only distinct ones sort them the minimum absolute difference will always be between adjacent sorted values So instead of checking every pair, we can use a TreeSet to maintain sorted unique values directly. ⚡ Approach Iterate through every possible k x k window Store its elements in a TreeSet If only one distinct value exists, answer is 0 Otherwise, scan adjacent values in sorted order and compute minimum difference ⏱ Time Complexity: O((m-k+1)(n-k+1) * k² log(k²)) 💾 Space Complexity: O(k²) 📌 Lesson: Sometimes the best solution is not the most “fancy” sliding window optimization, but the one that matches the constraints cleanly and correctly. #DSA #LeetCode #Java #Algorithms #ProblemSolving
Minimum Absolute Difference in Sliding Submatrix Java Solution
More Relevant Posts
-
Day: 73/365 📌 LeetCode POTD: Minimum Absolute Difference in Sliding Submatrix Medium Key takeaways/Learnings from this problem: 1. This problem shows how sliding window ideas extend to 2D, not just arrays, but it gets trickier to manage. 2. Maintaining a sorted structure (like multiset) helps in quickly finding min absolute differences in each window. 3. Big learning: brute force over every submatrix is too slow, so optimize by reusing previous window computations. 4. Overall, it’s a solid mix of 2D traversal + smart data structures to keep things efficient. #POTD #365DaysOfCode #DSA #Java #ProblemSolving #LearningInPublic #Consistency 🥷
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 20 Today’s focus: Sliding Window with frequency constraints. Problem solved: • Maximum Number of Occurrences of a Substring (LeetCode 1297) Concepts used: • Sliding Window technique • Frequency tracking using HashMap / array • Substring counting Key takeaway: The goal is to find the maximum frequency of any substring that satisfies: • At most maxLetters distinct characters • Length between minSize and maxSize A key observation simplifies the problem: We only need to check substrings of size minSize, because larger substrings will have equal or lower frequency. Using a sliding window of fixed size minSize, we: • Track character frequencies inside the window • Ensure the number of distinct characters ≤ maxLetters • Count valid substrings using a HashMap This avoids checking all possible substring sizes and reduces complexity significantly. This problem highlights how constraints can reduce the search space, making sliding window solutions more efficient. Continuing to strengthen pattern recognition and consistency in solving DSA problems. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 52 of DSA – Construct Product Matrix Solved a matrix problem where each cell stores the product of all other elements except itself, modulo 12345. 💡 Key Insight: Use prefix and suffix products to get the result for each position without division. ⚡ Approach: Compute product of elements before each index Compute product of elements after each index Multiply both to form the answer ⏱️ Time Complexity: O(n × m) 💾 Space Complexity: O(n × m) #DSA #LeetCode #Java #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 44 of Daily DSA 🚀 Solved LeetCode 1572: Matrix Diagonal Sum ✅ Problem: Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Approach: Used a two-pointer technique to traverse both diagonals in a single pass. Steps: Initialize two pointers → start = 0, end = n-1 Traverse each row: Add mat[i][start] (primary diagonal) Add mat[i][end] (secondary diagonal) Move pointers: start++, end-- If matrix size is odd → add center element once ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.53 MB Optimizing nested loops into a single pass can make your solution both cleaner and faster 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 56/100 | #100DaysOfDSA 🧠⚡ Today’s problem: String Compression A clean in-place array manipulation problem. Core idea: Compress consecutive repeating characters and store the result in the same array. Approach: • Traverse the array using a pointer • Count consecutive occurrences of each character • Write the character to the array • If count > 1 → write its digits one by one • Move forward and repeat Key insight: We don’t need extra space — just carefully manage read & write pointers. Time Complexity: O(n) Space Complexity: O(1) Big takeaway: In-place algorithms require precise pointer control but give optimal space efficiency. Mastering these improves real-world memory optimization skills. 🔥 Day 56 done. #100DaysOfCode #LeetCode #DSA #Algorithms #Strings #TwoPointers #InPlace #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
✨ Day 42 of 90 – Pattern Mastery Journey 🧠 Pattern : Alphabet Hash Pattern 💡 Approach: ✔ Created an n × n matrix using nested loops ✔ Printed alphabets only when row index equals column index (i == j) ✔ Filled all other positions with `#` ✔ Used ASCII logic `(char)('A' + i - 1)` to generate characters 🚀 This problem helped me understand how **diagonal conditions work in matrices** and how simple conditions can create clean structured patterns. #PatternMasteryJourney #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 39 of Daily DSA 🚀 Solved LeetCode 1446: Consecutive Characters ✅ Problem: The power of a string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return its power. Rules: * Substring must be non-empty * Substring must contain only one unique character * Return the maximum such length Approach: Used a simple linear scan to track the current streak of consecutive identical characters and update the maximum. Steps: 1. Initialize max and count both to 1 2. Iterate from index 1 onwards 3. If current character equals previous → increment count 4. Else → reset count to 1 5. Update max at every step 6. Return max ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 29 ms (Beats 2.02%) • Memory: 45.33 MB Sometimes the simplest sliding window — just two variables — is all you need to solve a problem cleanly. #DSA #LeetCode #Java #SlidingWindow #Strings #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
✨ Day 41 of 90 – Pattern Mastery Journey 🧠 Pattern:Reverse Alphabet Hash Pattern 💡 Approach: ✔ Used reverse looping (n → 1) to build the pattern ✔ Printed alphabets using ASCII logic `(char)('A' + i - 1)` ✔ Printed alphabet `i` times in each row ✔ Filled remaining positions with `#` using `(n - i)` ✔ Maintained proper structure and alignment 🚀 This problem helped me understand how reversing loops can change the entire pattern structure and improve control over output formatting. #PatternMasteryJourney #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 48 of Daily DSA 🚀 Solved LeetCode 48: Rotate Image ✅ Problem: Given an n x n matrix, rotate the image by 90° clockwise — in-place (without using extra space). Approach: Used a two-step transformation: Transpose the matrix Reverse each row Steps: Traverse upper triangle and swap → matrix[i][j] ↔ matrix[j][i] For each row: Use two pointers (left, right) Swap elements to reverse the row Matrix gets rotated in-place ⏱ Complexity: • Time: O(n²) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 43.56 MB In-place transformations are powerful — no extra space, just smart manipulation 💡 #DSA #LeetCode #Java #Matrix #Arrays #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 79: Sliding Submatrix Grinds 🔍 Problem 3567: Minimum Absolute Difference in Sliding Submatrix Today’s challenge was about finding the smallest gap between unique values within a shifting k×k window. It’s essentially a "Sliding Window" problem on a 2D scale. The Strategy: • Window Traversal: Iterated through every possible top-left coordinate where a k×k submatrix could fit. • Flatten & Sort: For each window, I gathered all elements into a list and sorted them. Sorting is the shortcut here, the minimum difference must exist between adjacent elements in a sorted list. • The "Unique" Check: Carefully calculated the absolute difference between neighboring elements, ignoring duplicates to find the true minimum gap. While the nested loops + sorting approach got the job done today, it’s a bit of a brute-force flex. It’s a solid reminder that sometimes "Make it work" is the first step before "Make it fast." 🚀 #LeetCode #Java #Algorithms #DataStructures #DailyCode
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