1200. Minimum Absolute Difference
Description
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 <= 105
- -106 <= arr[i] <= 106
💡 Hint 1:
Find the minimum absolute difference between two elements in the array.
💡 Hint 2:
The minimum absolute difference must be a difference between two consecutive elements in the sorted array.
Submitted Code
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_diff = float('inf')
result = []
for a, b in zip(arr, arr[1:]):
min_diff = min(min_diff, (b - a))
for a, b in zip(arr, arr[1:]):
if b - a == min_diff:
result.append([a, b])
return result
Runtime: 50 ms | Beats 66.07%
Memory: 31.41 MB | Beats 12.42%
Other Solutions
1st
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
minDiff = math.inf
dic = collections.defaultdict(list)
arr.sort() #O(n log n) time
for i in range(len(arr)-1): #O(n) time
diff = arr[i+1] - arr[i]
dic[diff].append([arr[i], arr[i+1]]) #O(n) space if all the pairs have the same minimum difference
minDiff = min(minDiff, diff)
return dic[minDiff]
time complexity: 𝑂(𝑛log𝑛)
space complexity: 𝑂(𝑛)
연속한 두 원소의 차이를 키로 하는 딕셔너리를 이용할 수도 있다. collections의 defaultdict는 키가 없을 때 KeyError가 나지 않고 자동으로 빈 리스트를 만들어주기 때문에 편리하다.