Minimum Absolute Difference Problem
Description
LeetCode Problem 1200.
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, bare fromarra < bb - aequals to the minimum absolute difference of any two elements inarr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]
Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
Constraints:
2 <= arr.length <= 10^5-10^6 <= arr[i] <= 10^6
Solution
Approach: Sort and Compare Neighbors
Checking every pair is O(n2), too slow for 10^5 numbers. Sort the array first. For a < b < c in sorted order, c - a = (c - b) + (b - a) is larger than either gap, so the minimum difference is always between two neighbors in the sorted array.
Two passes then do the job:
- Scan neighbors to find the smallest difference
best. - Scan again and collect every neighboring pair
[arr[i], arr[i + 1]]whose difference isbest.
The pairs come out in ascending order on their own, because the array is sorted, and each pair already has the smaller number first. The numbers are distinct, so best is at least 1.
In JavaScript, sort with (a, b) => a - b: the default sort compares numbers as strings and puts 10 before 9.
Complexity: O(n log n) time for the sort. O(1) extra space besides the sort and the output.
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
# After sorting, the closest pair is always two neighbors.
best = min(arr[i + 1] - arr[i] for i in range(len(arr) - 1))
return [[arr[i], arr[i + 1]] for i in range(len(arr) - 1) if arr[i + 1] - arr[i] == best]