I am stuck in one of Hackerrank problems with following problem description :-
You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the condition: (2,1), (3,2), (4,3). So function pairs should return value 3.
We have to implement pairs function with following parameters :-
k: an integer, the target difference
arr: an array of integers
Constraints :-
1> Each Integer in arr[i] will be unique and positive.
2> target k will also be positive.
My below function implementation is failing one of 18 test cases because of the wrong result. Can anyone please help me debug the issue :-
def binSearch(target,arr):
lower = 0
upper = len(arr)-1
while lower <= upper:
mid = int((lower + upper)/2)
if(arr[mid] == target):
return 1
elif(arr[mid] > target):
upper = mid - 1
elif(arr[mid] < target):
lower = mid + 1
return -1
def pairs(k, arr):
arr.sort()
count = 0
for i in range(len(arr)):
target = abs(arr[i] - k)
if(arr[i] == target):
pass
elif(binSearch(target,arr) == 1):
count += 1
return count