Minimum Absolute Difference (LeetCode 1200): Solution and Explanation
Given distinct integers, return every pair [a, b] whose difference b - a equals the smallest difference between any two elements, in ascending order.
Intuition
Checking every pair is O(n^2). Sorting removes most of that work: once values are in order, the closest pair must be two neighbours, because any pair further apart spans at least one neighbour gap that is no bigger.
So sort, then look at each gap between neighbours exactly once. Keep the smallest gap seen so far and the list of pairs that have it.
A smaller gap makes every pair collected so far wrong, so throw them away and start a new list. An equal gap just joins the list. Because the scan runs left to right, the pairs come out in ascending order without any extra sorting.
Approach: Sort, then scan neighbours
- Sort arr in ascending order.
- Set
bestto infinity andresultto an empty list. - For each i from 1 to n - 1, let
diff = arr[i] - arr[i - 1]. - If
diff < best, setbest = diffandresult = [[arr[i - 1], arr[i]]]. Ifdiff == best, append the pair. - Return result.
Step-by-step example
arr = [3,8,-10,23,19,-4,-14,27]
- Sorted: [-14,-10,-4,3,8,19,23,27].
- Gap -10 - (-14) = 4 is the first, so best = 4 and result = [[-14,-10]].
- Gaps 6, 7, 5 and 11 are all bigger than 4, so they are skipped.
- Gap 23 - 19 = 4 ties, add [19,23]. Gap 27 - 23 = 4 ties, add [23,27].
- Result: [[-14,-10],[19,23],[23,27]].
Code: Python, Java, C++
1class Solution:
2 def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
3 arr.sort()
4 best = float("inf")
5 result = []
6 for i in range(1, len(arr)):
7 diff = arr[i] - arr[i - 1]
8 if diff < best:
9 best = diff
10 result = [[arr[i - 1], arr[i]]]
11 elif diff == best:
12 result.append([arr[i - 1], arr[i]])
13 return result1class Solution {
2 public List<List<Integer>> minimumAbsDifference(int[] arr) {
3 Arrays.sort(arr);
4 int best = Integer.MAX_VALUE;
5 List<List<Integer>> result = new ArrayList<>();
6 for (int i = 1; i < arr.length; i++) {
7 int diff = arr[i] - arr[i - 1];
8 if (diff < best) {
9 best = diff;
10 result = new ArrayList<>();
11 result.add(Arrays.asList(arr[i - 1], arr[i]));
12 } else if (diff == best) {
13 result.add(Arrays.asList(arr[i - 1], arr[i]));
14 }
15 }
16 return result;
17 }
18}1class Solution {
2public:
3 vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
4 sort(arr.begin(), arr.end());
5 int best = INT_MAX;
6 vector<vector<int>> result;
7 for (int i = 1; i < (int)arr.size(); i++) {
8 int diff = arr[i] - arr[i - 1];
9 if (diff < best) {
10 best = diff;
11 result.clear();
12 result.push_back({arr[i - 1], arr[i]});
13 } else if (diff == best) {
14 result.push_back({arr[i - 1], arr[i]});
15 }
16 }
17 return result;
18 }
19};Time and space complexity
O(n log n)
Sorting dominates; the scan over neighbours is O(n).
O(1)
Only a few variables beyond the output (the sort itself may use O(log n) stack).
Other approaches
Two passes (time O(n log n), space O(1))
First scan the sorted array to find the minimum gap, then scan again and collect every neighbour pair with that gap. Avoids resetting the list, same complexity.
Counting sort (time O(n + R), space O(R))
Values lie in [-10^6, 10^6], so a counting sort over that range can replace the comparison sort. It is linear in n plus the value range, which only pays off for very large n.
Brute force (time O(n^2), space O(1))
Compare all pairs to find the minimum, then collect and sort the matching pairs. Too slow for n up to 10^5.
Common mistakes
- Appending a pair when a smaller gap appears without clearing the old pairs first.
- Comparing non-adjacent elements after sorting, which only adds work.
- Returning pairs as [larger, smaller]. Each pair must be [a, b] with a < b.
Frequently asked questions
Why only adjacent elements?
For sorted values a < b < c, c - a = (b - a) + (c - b), which is larger than either neighbour gap. So a non-adjacent pair can never be strictly closest.
Do I need to sort the result?
No. The scan visits pairs left to right in a sorted array, so they are produced in ascending order.
Can the difference overflow?
No. Values are within [-10^6, 10^6], so a gap is at most 2 * 10^6, well inside a 32-bit integer.