Code Logo

Minimum Absolute Difference

Published at24 Jul 2026
Easy 0 views
Like0

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference. Return the pairs sorted in ascending order by their first element, then by their second element. Each pair [a,b] should have a < b.

Sort the array first. The minimum absolute difference can only occur between adjacent elements in a sorted array. Find the minimum difference by scanning adjacent pairs. Then collect all pairs that match this minimum difference.

After sorting, the algorithm is simple: iterate through adjacent pairs, track the minimum difference, then make a second pass to collect pairs with that exact difference. This runs in O(n log n) due to sorting plus O(n) for the scans.

Edge cases include an array with only two elements (the only pair is the answer), all elements having the same difference (all adjacent pairs qualify), and large arrays with many pairs sharing the minimum difference.

Sorting the array guarantees that the minimum absolute difference is always between adjacent elements. This is because for any sorted array, the absolute difference between non-adjacent elements is at least as large as the sum of intermediate adjacent differences.

Example Input & Output

Example 1
Input
[1,2]
Output
[[1,2]]
Explanation

Min diff 1.

Example 2
Input
[3,8,-10,23,19,-4,-14,27]
Output
[[-14,-10],[19,23],[23,27]]
Explanation

Min diff 4, 3 pairs.

Example 3
Input
[1,5]
Output
[[1,5]]
Explanation

Only two elements.

Example 4
Input
[4,2,1,3]
Output
[[1,2],[2,3],[3,4]]
Explanation

Min diff 1, 3 pairs.

Example 5
Input
[1,3,6,10,15]
Output
[[1,3]]
Explanation

Min diff 2, only [1,3].

Algorithm Flow

Recommendation Algorithm Flow for Minimum Absolute Difference
Recommendation Algorithm Flow for Minimum Absolute Difference

Solution Approach

Sort array. Find min diff via adjacent scan. Collect pairs with that diff.

function solution(arr) {
  arr.sort(function(a,b){return a-b;});
  var minDiff = arr[1] - arr[0];
  for (var i = 2; i < arr.length; i++) {
    var diff = arr[i] - arr[i-1];
    if (diff < minDiff) minDiff = diff;
  }
  var result = [];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] - arr[i-1] === minDiff) {
      result.push([arr[i-1], arr[i]]);
    }
  }
  return result;
}

Time O(n log n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public List<List<Integer>> solution(int[] arr) {
        Arrays.sort(arr);
        int md=arr[1]-arr[0];
        for (int i=2;i<arr.length;i++) {
            int d=arr[i]-arr[i-1];
            if (d<md) md=d;
        }
        List<List<Integer>> res=new ArrayList<>();
        for (int i=1;i<arr.length;i++) {
            if (arr[i]-arr[i-1]==md) res.add(Arrays.asList(arr[i-1],arr[i]));
        }
        return res;
    }
}