Minimum Absolute Difference in an Array

Given an array of integers, find and print the minimum absolute difference between any two elements in the array.

For example,

Input: -59 -36 -13 1 -53 -92 -2 -96 -54 75

Output: 1

// Complete the minimumAbsoluteDifference function below.
function minimumAbsoluteDifference(arr) {

    let min_difference = Number.MAX_VALUE;
    // sorts the given array in an ascending order
    arr.sort((a,b) => a-b);
    
    for (let i = 0; i < arr.length - 1; i++) {
        min_difference = Math.min(Math.abs(arr[i] - arr[i+1]), min_difference);
      
        // Return early as 0 is the minimum absolute difference
        if (min_difference == 0)
            return 0;
    }
    return min_difference;
}

The solution to the above problem is using a greedy solution as we are finding local minimum at every step to find the global minimum. You may refer to below article to read more about them.

https://en.wikipedia.org/wiki/Maxima_and_minima

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *