Minimum Absolute Difference
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
Min diff 1.
Min diff 4, 3 pairs.
Only two elements.
Min diff 1, 3 pairs.
Min diff 2, only [1,3].
Algorithm Flow

Solution Approach
Sort array. Find min diff via adjacent scan. Collect pairs with that diff.
Time O(n log n), Space O(n).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
