• + 1 comment

    Python3 Optimal Solution:

    def pairs(k, arr):

    from collections import defaultdict
    arr_elements=set(arr)
    hmap=defaultdict(int)
    
    for i in range(len(arr)):
        if arr[i]+k in arr_elements and (arr[i], arr[i]+k) not in hmap:
            hmap[(arr[i], arr[i]+k)]+=1
    
        if arr[i]-k in arr_elements and (arr[i]-k, arr[i]) not in hmap:
            hmap[(arr[i]-k, arr[i])]+=1
    
    return sum(hmap.values())