I am trying to solve a problem of finding all the pairs of a list that have a sum of k, in 0(nlogn) time.
I first sort the list (I use merge sort) and then do binary search for each element x of the array to look for (k-x). This works for regular lists, but for example if I have a list like [1,1,1,1] and k=2, my code returns 4 instead of 6. I was wondering if there is any variation of binary search that allows for the above to happen. I tried googling around but I couldn't find anything that covered this question.
For reference this is my code ( I did not include merge sort since it's not relevant)
def binary_search(alist, item):
if len(alist)==0:
return False
else:
mid=len(alist)//2
if alist[mid]==item:
return True
else:
if item< alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
def find_pairs(alist, k):
count=0
for i in range(len(alist)):
if binary_search(alist,(k-alist[i])):
count+=1
return(count)