Problem of the Day: Minimum Absolute Difference (LeetCode) Today I tackled the classic Minimum Absolute Difference problem. The goal is simple yet elegant: . Given an array of integers, find all pairs with the smallest absolute difference. Here’s my clean and efficient Java solution: ...................................................................................................................................................... class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { Arrays.sort(arr); int min=Integer.MAX_VALUE; for(int i=1;i<arr.length;i++){ min=Math.min(min,(arr[i]-arr[i-1])); } List<List<Integer>> l=new ArrayList<>(); for(int i=1;i<arr.length;i++){ if((arr[i]-arr[i-1])==min){ l.add(Arrays.asList(arr[i - 1], arr[i])); } } return l; } } ........................................................................................................................................................ Key Takeaways: Sorting simplifies the problem by ensuring differences are checked only between consecutive elements. A two-pass approach (first to find the minimum difference, second to collect pairs) keeps the logic clear and modular. Time complexity: O(n log n) due to sorting, which is optimal here. ✨ Solving problems like these sharpens algorithmic thinking and prepares us for real-world scenarios where efficiency matters. #Java #LeetCode #ProblemSolving #CodingChallenge #DataStructuresAndAlgorithms
Java Solution: Minimum Absolute Difference Problem
More Relevant Posts
-
𝐉𝐚𝐯𝐚 𝐢𝐬 𝐚𝐥𝐰𝐚𝐲𝐬 𝐏𝐚𝐬𝐬-𝐛𝐲-𝐕𝐚𝐥𝐮𝐞. 𝐒𝐨 𝐰𝐡𝐲 𝐝𝐢𝐝 𝐦𝐲 𝐚𝐫𝐫𝐚𝐲 𝐜𝐡𝐚𝐧𝐠𝐞? 🤔 I wrote a simple program to test how Java handles method arguments. [1] Declared an array 𝐚𝐫𝐫 in 𝐦𝐚𝐢𝐧. [2] Passed it to a 𝐜𝐡𝐚𝐧𝐠𝐞(𝐢𝐧𝐭[] 𝐧𝐮𝐦𝐬) method. [3] Modified 𝐧𝐮𝐦𝐬[𝟎] AND 𝐧𝐮𝐦𝐬[𝟏] inside the method. [4] The original 𝐚𝐫𝐫 was updated. 𝐓𝐡𝐞 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧: Java is strictly Pass-by-Value. When I passed 𝐚𝐫𝐫, I didn't pass the object itself. I passed a copy of the reference variable. [A] Both the original 𝐚𝐫𝐫 and the method parameter 𝐧𝐮𝐦𝐬 hold the same memory address (pointing to the same array object in the Heap). [B] So, when 𝐧𝐮𝐦𝐬 modifies the data, it modifies the shared object. Understanding Stack (references) vs. Heap (objects) is crucial for avoiding bugs. #Java #MemoryManagement #SoftwareEngineering #CodingInterviews #LearningInPublic #BackendDevelopment #DataStructures #Coding #WeMakeDevs #100DaysOfCode #IntelliJ
To view or add a comment, sign in
-
-
🛑 𝗙𝗶𝗻𝗮𝗹 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲: 𝗖𝗹𝗲𝗮𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗖𝗼𝗻𝗳𝘂𝘀𝗶𝗼𝗻 In the Java world, these three keywords sound almost identical, but they serve completely different purposes. If you're just cleaning up your code, here is the breakdown you need. 1. 𝗙𝗶𝗻𝗮𝗹 (𝗧𝗵𝗲 𝗞𝗲𝘆𝘄𝗼𝗿𝗱) Used to define 𝗶𝗺𝗺𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 or restrictions. Think of it as "the last version" of something: • 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀: Makes them constants (cannot be reassigned). • 𝗠𝗲𝘁𝗵𝗼𝗱𝘀: Prevents them from being overridden by subclasses. • 𝗖𝗹𝗮𝘀𝘀𝗲𝘀: Prevents inheritance (e.g., the String class is final). 2. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 (𝗧𝗵𝗲 𝗕𝗹𝗼𝗰𝗸) Used in 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗵𝗮𝗻𝗱𝗹𝗶𝗻𝗴 (try-catch-finally). It represents "guaranteed execution": • The code inside a finally block runs 𝗻𝗼 𝗺𝗮𝘁𝘁𝗲𝗿 𝘄𝗵𝗮𝘁—whether an exception was thrown or not. • 𝗕𝗲𝘀𝘁 𝗨𝘀𝗲: Closing file streams, database connections, or releasing resources to prevent memory leaks. 3. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲 (𝗧𝗵𝗲 𝗠𝗲𝘁𝗵𝗼𝗱) A protected method inherited from the Object class: • It is invoked by the 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 just before an object is destroyed. • 𝗦𝘁𝗮𝘁𝘂𝘀: 𝗗𝗲𝗽𝗿𝗲𝗰𝗮𝘁𝗲𝗱 since Java 9. • 𝗪𝗵𝘆? It is unpredictable, unreliable, and can cause significant performance issues. Modern Java favors try-with-resources for cleanup. #Java #Programming #Backend #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
#Day 63: LeetCode 1984 - Minimum Difference Between Highest and Lowest of K Scores Code:- import java.util.Arrays; class Solution { public int minimumDifference(int[] nums, int k) { // Step 1: Handle the edge case where only one score is picked if (k == 1) return 0; // Step 2: Sort the scores to bring close values together Arrays.sort(nums); int minDiff = Integer.MAX_VALUE; // Step 3: Slide a window of size k through the array // The window starts at 'i' and ends at 'i + k - 1' for (int i = 0; i <= nums.length - k; i++) { int currentDiff = nums[i + k - 1] - nums[i]; // Step 4: Update the global minimum difference if (currentDiff < minDiff) { minDiff = currentDiff; } } return minDiff; } } #The Strategy: ->Sort the scores to align them by magnitude. ->Apply a Sliding Window of size $k$ to look at every possible 'cluster' of scores. ->Calculate the spread (Max - Min) for each cluster and capture the minimum. #100DaysOfCode #Java #SoftwareEngineering #Algorithms #LeetCode #SDE #ProblemSolving #SlidingWindow"
To view or add a comment, sign in
-
-
𝐓𝐡𝐢𝐬 𝐜𝐨𝐝𝐞 𝐬𝐧𝐢𝐩𝐩𝐞𝐭 𝐢𝐬 𝐞𝐧𝐨𝐮𝐠𝐡 𝐭𝐨 𝐜𝐨𝐧𝐟𝐮𝐬𝐞 𝐬𝐨𝐦𝐞𝐨𝐧𝐞 𝐰𝐢𝐭𝐡 𝐉𝐚𝐯𝐚. 😁 Let me introduce you to the concept of wrapper classes and autoboxing first. 𝐖𝐑𝐀𝐏𝐏𝐄𝐑 𝐂𝐋𝐀𝐒𝐒𝐄𝐒: These are classes used to wrap primitive values so we can treat them like objects. This is essential for the Collection framework (like ArrayList), which only works with objects. 𝐀𝐔𝐓𝐎𝐁𝐎𝐗𝐈𝐍𝐆: The process of converting primitive values to wrapper objects is implicit. We don't need the new keyword. Now let's discuss the code: 𝐂𝐎𝐃𝐄 1: 𝘪𝘯𝘵 𝘢 = 100; 𝘪𝘯𝘵 𝘣 = 100; These are primitive values. For primitives, the == operator compares the actual values. Since both are 100, the output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 2: Integer wrapper classes have an Integer Cache. By default, Java caches all Integer objects in the range of -128 to 127. 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘱 = 100; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘲 = 100; Since 100 is in the cache, Java points both variables to the same object memory location. The output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 3: 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘺 = 128; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘻 = 128; Because 128 is outside the cache range, Java creates two distinct objects in memory. Since == compares memory references for objects, the output is 𝐟𝐚𝐥𝐬𝐞. ~Anuprash Gautam 🍵 𝘒𝘦𝘦𝘱 𝘭𝘦𝘢𝘳𝘯𝘪𝘯𝘨 𝘢𝘯𝘥 𝘣𝘳𝘦𝘸𝘪𝘯𝘨 𝘤𝘰𝘧𝘧𝘦𝘦.😊 #Java #programming #autoboxing #oops
To view or add a comment, sign in
-
-
𝐎𝐮𝐭 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐎𝐥𝐝, 𝐈𝐧 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐍𝐞𝐰 Java has evolved, and with it, a simpler, more modern approach to writing immutable data types records. In previous versions of Java, creating simple value objects required a significant amount of boilerplate code. 𝐓𝐡𝐞 𝐎𝐥𝐝 𝐖𝐚𝐲 public class Point { private final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object obj) { ... } @Override public int hashCode() { ... } @Override public String toString() { ... } } 𝐓𝐡𝐞 𝐍𝐞𝐰 𝐖𝐚𝐲 Now, with records, all that boilerplate is handled for you. A record automatically generates A constructor equals(), hashCode(), and toString() methods public record Point(int x, int y) {} When you have simple value objects with immutable data. When you don’t need additional logic like setters, mutable fields, or complex methods. #Java #JavaRecords #Programming #Coding #ImmutableData #BoilerplateCode #CleanCode #Java14 #ModernJava #SoftwareDevelopment #CodeSimplification #ObjectOrientedProgramming #JavaBestPractices #JavaTips #JavaDeveloper #TechTrends #DeveloperLife #JavaSyntax #JavaProgramming #RecordClass #TechInnovation #CodingTips #JavaCommunity
To view or add a comment, sign in
-
🚀 Minimum Absolute Difference (Optimized Java Approach) Today I revisited a classic array problem and implemented a clean, optimized solution using sorting and a two-pass strategy. Leetcode Problem link:https://lnkd.in/gWtQD_FX 💡 Key idea: Sort the array first Adjacent elements now give the minimum possible differences Use: Pass 1 → find the minimum absolute difference Pass 2 → collect all pairs with that difference ✅ Why this approach? Easy to reason about Avoids unnecessary condition checks Optimal time complexity ⏱️ Complexity: Time: O(n log n) (sorting dominates) Space: O(1) extra (excluding output) #Java #DataStructures #Algorithms #LeetCode #ProblemSolving #CleanCode #LinkedList #Sorting #OptimizedCode
To view or add a comment, sign in
-
-
#Day 64:- LeetCode 1200 #Code import java.util.*; class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { // Step 1: Sort the array to bring numerically close values together Arrays.sort(arr); List<List<Integer>> result = new ArrayList<>(); int minDiff = Integer.MAX_VALUE; // Step 2: Iterate once to find the minimum difference and collect pairs for (int i = 0; i < arr.length - 1; i++) { int currentDiff = arr[i+1] - arr[i]; if (currentDiff < minDiff) { // Found a new smaller difference; reset result and update minDiff minDiff = currentDiff; result.clear(); result.add(Arrays.asList(arr[i], arr[i+1])); } else if (currentDiff == minDiff) { // Found another pair with the same minimum difference result.add(Arrays.asList(arr[i], arr[i+1])); } } return result; } } #Day 63/100: Today I solved LeetCode 1200 - Minimum Absolute Difference. In software engineering, we often face problems that look like O(N^2) at first glance. Finding the 'closest' elements in a dataset is a classic example. But by introducing Order (Sorting), we can collapse that complexity significantly.
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: 454. 4Sum II Today I solved 4Sum II (Medium) on LeetCode using an optimized approach with HashMap in Java. 🔹 Problem Summary: Given four integer arrays nums1, nums2, nums3, and nums4, count the number of tuples (i, j, k, l) such that: nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 🔹 Approach Used: Instead of using brute force (O(n⁴)), I optimized it to O(n²) using a HashMap: 1️⃣ Store all possible sums of nums1[i] + nums2[j] in a HashMap with frequency. 2️⃣ For each pair from nums3[k] + nums4[l], check if -(sum) exists in the map. 3️⃣ Add the frequency to the count. 💡 This reduces time complexity from O(n⁴) → O(n²), which is a huge improvement for large inputs. 🔹 Key Concepts Practiced: ✔ HashMap ✔ Frequency counting ✔ Time complexity optimization ✔ Thinking in terms of pair sums Consistent DSA practice is helping me improve my problem-solving patterns and optimization mindset. 💪 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Stop guessing, start profiling. "My Java app is slow." 🎭As a Team Lead, I hear this a lot. The natural instinct for many developers is to immediately jump into the code and start refactoring loops or swapping ArrayLists for LinkedLists. 💁The Reality: 90% of the time, the bottleneck isn't where you think it is. 👉In a high-scale environment, performance optimization isn't about "coding faster"—it’s about observability. If you aren't using the right tools, you're just throwing spaghetti at the wall. My Friday Performance Checklist: * Flame Graphs are your friend: Use async-profiler or JFR (Java Flight Recorder). Visualizing CPU tracks and allocation pressure saves hours of blind debugging. * Check the GC overhead: Is your heap struggling? Sometimes a simple tuning of the G1GC regions or switching to ZGC/Shenandoah can drop your P99 latency instantly. * Database & Network IO: Java is rarely the bottleneck alone. Check for N+1 queries or un-optimized connection pools before rewriting your business logic. * Mechanical Sympathy: Understand how the JVM interacts with the underlying hardware. L1/L2 cache misses matter more than you'd think in high-throughput systems. Clean code is great, but performant code keeps the lights on and the users happy. What’s the weirdest performance bottleneck you’ve ever uncovered in a production environment? Let’s swap horror stories in the comments. 👇 #JavaPerformance #JVM #SoftwareEngineering
To view or add a comment, sign in
-
📌 Spring Boot Annotation Series – Part 14 ✅ @Qualifier annotation The @Qualifier annotation is used to resolve confusion when multiple beans of the same type exist 👇 🔹 Why do we need @Qualifier? When there are multiple implementations of the same interface, Spring gets confused about which one to inject. 👉 That’s where @Qualifier helps. 🔹 Example Scenario public interface PaymentService { void pay(); } @Service("upiService") public class UpiPaymentService implements PaymentService { public void pay() { } } @Service("cardService") public class CardPaymentService implements PaymentService { public void pay() { } } @RestController public class PaymentController { @Autowired @Qualifier("upiService") private PaymentService paymentService; } 👉 Here we are clearly telling Spring to inject UpiPaymentService. 🔹 What happens without @Qualifier? ❌ Spring throws: NoUniqueBeanDefinitionException Because it finds more than one matching bean. 🔹 In simple words @Qualifier helps Spring choose the correct bean when multiple beans of the same type are available. 👉 🧠 Quick Understanding Used with @Autowired Resolves multiple bean conflict Avoids NoUniqueBeanDefinitionException Makes dependency injection clear #SpringBoot #Java #Qualifier #DependencyInjection #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
Explore related topics
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