Minimum Absolute Difference in an Array

Sort by

recency

|

62 Discussions

|

  • + 0 comments

    My rust solution:

    fn minimumAbsoluteDifference(arr: &mut [i32]) -> i32 {
        arr.sort();
    
        arr.windows(2)
            .map(|window| (window[0] - window[1]).abs())
            .min()
            .unwrap()
    
  • + 0 comments

    Python3 1 liner

    return min(map(lambda p: p[1] - p[0], itertools.pairwise(sorted(arr))))
    
  • + 0 comments

    def minimumAbsoluteDifference(arr):

    n_arr = []
    arr.sort()
    for i in range(len(arr) - 1):
        c = arr[i]
        n = arr[i + 1]
        d = abs(c - n)
        n_arr.append(d)
    return min(n_arr)
    
  • + 0 comments

    Initial Approach: Evaluate all combinations in the array using two nested loops, given that . This approach is correct but inefficient with a time complexity of due to the number of comparisons .

    Optimized Approach: Pre-sort the array. The minimum distance for an element is determined by its immediate neighbors and , enabling a linear search. This approach is not only correct but also more efficient with a time complexity of , which is the sum of the sorting time and the linear search time .

  • + 0 comments

    Java and O(n log n)

     Collections.sort(arr);
            int minDiff = Integer.MAX_VALUE;
            for (int i = 1; i < arr.size(); i++) {
                int diff = Math.abs(arr.get(i) - arr.get(i - 1));
                if (diff < minDiff) {
                    minDiff = diff;
                }
            }
            return minDiff;