VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-minimum-absolute-difference-array-element/

⇱ Sum of minimum absolute differences in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of minimum absolute differences in an array

Last Updated : 24 Apr, 2025

Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: 

  • Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <= j < n and j != i and abs is the absolute value. 

Examples: 

Input : arr = [4, 1, 5]
Output : 5
Explanation: Sum of minimum absolute differences is |4-5| + |1-4| + |5-4| = 1 + 3 + 1 = 5

Input : arr = [5, 10, 1, 4, 8, 7]
Output : 9
Explanation: Sum of minimum absolute differences is
|5-4| + |10-8| + |1-4| + |4-5| + |8-7| + |7-8| = 1 + 2 + 3 + 1 + 1 + 1 = 9

Input : arr = [12, 10, 15, 22, 21, 20, 1, 8, 9]
Output : 18

[Naive Approach] Using 2 Nested Loops - O(n^2) time and O(1) space

The idea is to iterate through each element in the array and find the minimum absolute difference between that element and any other element in the array. For each element, we check all other elements, find the smallest absolute difference, and add it to our sum.


Output
5

[Expected Approach] Using Sorting - O(n Log n) time and O(1) space

The idea is to sort the array first so that elements with similar values are placed adjacently. After sorting, for any element, its minimum absolute difference will be with either its left neighbor or its right neighbor.

Step by step approach:

  1. Sort the input array to place similar elements next to each other.
  2. Calculate minimum difference for first element (only has right neighbor) and minimum difference for last element (only has left neighbor).
  3. For each middle element, find minimum of differences with left and right neighbors.
  4. Sum all these minimum differences to get the final result.

Output
5
Comment
Article Tags:
Article Tags: