LeetCode 1200: Minimum Absolute Difference Solution

Master LeetCode problem 1200 (Minimum Absolute Difference), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1200. Minimum Absolute Difference

Problem Explanation

Explanation

To solve this problem, we can first sort the input array. Then, we iterate through the array to find the minimum absolute difference between adjacent elements. Finally, we iterate through the array again to find pairs of elements that have this minimum absolute difference.

  • Sort the input array.
  • Initialize a variable minDiff to store the minimum absolute difference.
  • Initialize an empty list result to store the pairs with the minimum absolute difference.
  • Find the minimum absolute difference by iterating through the sorted array and comparing adjacent elements.
  • Iterate through the sorted array again to find pairs with the minimum absolute difference and add them to the result list.

Time complexity: O(n log n) where n is the number of elements in the array due to sorting. Space complexity: O(n) for the result list.

Solution Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> minimumAbsDifference(int[] arr) {
        Arrays.sort(arr);
        int minDiff = Integer.MAX_VALUE;
        List<List<Integer>> result = new ArrayList<>();
        
        for (int i = 1; i < arr.length; i++) {
            minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);
        }
        
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] - arr[i - 1] == minDiff) {
                result.add(Arrays.asList(arr[i - 1], arr[i]));
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1200 (Minimum Absolute Difference)?

This page provides optimized solutions for LeetCode problem 1200 (Minimum Absolute Difference) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1200 (Minimum Absolute Difference)?

The time complexity for LeetCode 1200 (Minimum Absolute Difference) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1200 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1200 in Java, C++, or Python.

Back to LeetCode Solutions