Minimum Absolute Difference ( LeetCode ) Problem Solution.
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 up 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 :-
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
ans=[]
dif=0
arr.sort()
print(arr)
for i in range(len(arr)-1):
if(arr[i]<arr[i+1]):
d=arr[i+1]-arr[i]
if(dif>0):
if(d<dif):
ans=[]
ans.append([arr[i],arr[i+1]])
dif=d
elif(d==dif):
ans.append([arr[i],arr[i+1]])
else:
dif=d
ans.append([arr[i],arr[i+1]])
return ans
Runtime: 400 ms, faster than 26.36% of Python3 online submissions for Minimum Absolute Difference.
Memory Usage: 27.9 MB, but 100.00% of Python3 online submissions for Minimum Absolute Difference.
0 Comments