The problem. Given an array of distinct integers arr, find the minimum absolute difference between any two elements, and return every pair [a, b] with that difference, with a < b, in ascending order of a.
arr = [4, 2, 1, 3] -> [[1,2], [2,3], [3,4]]
arr = [1, 3, 6, 10, 15] -> [[1,3]]
arr = [3, 8, -10, 23, 19, -4, -14, 27] -> [[-14,-10], [19,23], [23,27]]In sorted order, if a < b < c, then c − a is bigger than both b − a and c − b. So a pair that isn't adjacent can never be the closest — some value in between is closer to each of them. That leaves only the n − 1 gaps between neighbours: find the smallest, then collect every neighbouring pair with that gap. Because we walk in sorted order, the pairs come out already in the required order.
function minimumAbsDifference(arr) { let best = Infinity; for (let i = 0; i < arr.length; i++) for (let j = i + 1; j < arr.length; j++) best = Math.min(best, Math.abs(arr[i] - arr[j])); const pairs = []; for (let i = 0; i < arr.length; i++) for (let j = i + 1; j < arr.length; j++) if (Math.abs(arr[i] - arr[j]) === best) pairs.push([Math.min(arr[i], arr[j]), Math.max(arr[i], arr[j])]); return pairs.sort((p, q) => p[0] - q[0]);}Time O(n²), space O(n²) in the worst case for the pairs list. Every pair is compared, though only neighbours ever matter.
Sort, scan the gaps between neighbours for the smallest, then collect those pairs.
function minimumAbsDifference(arr) { const a = [...arr].sort((x, y) => x - y); let best = Infinity; for (let i = 1; i < a.length; i++) best = Math.min(best, a[i] - a[i - 1]); // the closest pair is always adjacent const pairs = []; for (let i = 1; i < a.length; i++) { if (a[i] - a[i - 1] === best) pairs.push([a[i - 1], a[i]]); } return pairs;}Time O(n log n), space O(n) for the sorted copy and the answer. Two linear passes after the sort.
When values lie in a small range, a counting sort makes approach 2 linear: O(n + range).
abs is needed.int; use long if the constraints allow it.