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, b
are from arr
a < b
b - a
equals to the minimum absolute difference of any two elements in arr
For example:
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.
arr = [1,3,6,10,15]
Output: [[1,3]]
arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
class Solution:
def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:
arr.sort()
min_diff = float('inf')
result = []
for i in range(len(arr) - 1):
diff = arr[i+1] - arr[i]
if diff < min_diff:
min_diff = diff
result = [[arr[i], arr[i+1]]]]
elif diff == min_diff:
result.append([arr[i], arr[i+1]])
return result
The naive solution involves calculating the absolute difference between every pair of numbers in the array and keeping track of the minimum difference found so far. Then, iterate through all pairs again to collect those pairs with the minimum difference.
The optimal solution sorts the array first. After sorting, the minimum absolute difference can only occur between adjacent elements. Iterate through the sorted array and calculate the difference between adjacent elements. Keep track of the minimum difference found so far and the pairs that have that minimum difference.
arr
.diff < min_diff
to diff <= min_diff
and making sure to not add duplicate pairs to the result.long
in Java or int64
in Python) can help prevent this.