Minimum Absolute Difference in an Array

Sort by

recency

|

704 Discussions

|

  • + 0 comments
    def minimumAbsoluteDifference(arr):
        arr.sort()
        a=arr[0]-arr[1]
        b=-10000000000
        for i in range(2,n):
            b=max(b,arr[i-2]-a-arr[i])
            a=arr[i-2]-a-arr[i]
        return abs(b)
    
  • + 0 comments

    Here is my c++ solution, you can find the explanation here : https://youtu.be/6SnD7A1TbJQ

    int minimumAbsoluteDifference(vector<int> arr) {
        sort(arr.begin(), arr.end());
        int result = INT_MAX;
        for(int i = 1; i < arr.size(); i++){
            int d = arr[i] - arr[i-1];
            if( d < result) result = d;
        }
        return result;
    }
    
  • + 0 comments

    My Java solution with o(n log n + n) time complexity and o(1) space:

    public static int minimumAbsoluteDifference(List<Integer> arr) {
            // goal: determine the min abs val between any two pairs in arr
            Collections.sort(arr); //sort arr ascending
            int min = Integer.MAX_VALUE;
            for(int i = 1; i < arr.size(); i++){
                int currentMin = arr.get(i) - arr.get(i - 1); 
                if(currentMin < min) min = currentMin;
            }
            return min;
        }
    
  • + 0 comments

    Here is my Python solution!

    def minimumAbsoluteDifference(arr):
        arr.sort()
        differences = []
        for i in range(1, len(arr)):
            differences.append(abs(arr[i] - arr[i - 1]))
        return min(differences)
    
  • + 0 comments
        public static int minimumAbsoluteDifference(List<Integer> arr) {
            // Sort the array
            Collections.sort(arr); 
            
            int absMin = Integer.MAX_VALUE;
            for (int i = 1; i < arr.size(); i++) {
                int absDiff = Math.abs(arr.get(i) - arr.get(i - 1));
                absMin = Math.min(absMin, absDiff);
            }
            
            return absMin;
        }