You are given a list of distinct integers arr
and you want to find all pairs of elements with the minimum absolute difference of any two elements. The output should be a list of pairs sorted in ascending order.
Given a list of n
distinct integers, find all pairs of elements with the minimum absolute difference.
Example:
Input: arr = [4, 2, 1, 3]
Output: [[1, 2], [2, 3], [3, 4]]
def minimumAbsDifference(arr):
arr.sort()
min_diff = float('inf')
result = []
# Find the minimum absolute difference
for i in range(1, len(arr)):
diff = arr[i] - arr[i-1]
if diff < min_diff:
min_diff = diff
# Collect all pairs with the minimum absolute difference
for i in range(1, len(arr)):
if arr[i] - arr[i-1] == min_diff:
result.append([arr[i-1], arr[i]])
return result
# Example usage:
arr = [4, 2, 1, 3]
print(minimumAbsDifference(arr)) # Output: [[1, 2], [2, 3], [3, 4]]
Thus, the overall time complexity is [ O(n \log n) + O(n) + O(n) = O(n \log n) ]
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?