From 2290ff9361069b90e802594715fb290af7addf0d Mon Sep 17 00:00:00 2001 From: siddwarr Date: Tue, 3 Oct 2023 18:29:32 +0530 Subject: [PATCH] added pairs_with_given_sum --- .../arrays/pairs_with_given_sum.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 data_structures/arrays/pairs_with_given_sum.py diff --git a/data_structures/arrays/pairs_with_given_sum.py b/data_structures/arrays/pairs_with_given_sum.py new file mode 100644 index 000000000..677a99be1 --- /dev/null +++ b/data_structures/arrays/pairs_with_given_sum.py @@ -0,0 +1,48 @@ +""" +Author : Siddharth Warrier +Date : October 3, 2023 + +Task: +Count the no of pairs in a given array with given sum + +Implementation notes: Using hashing +The idea is that we hash the array in a dictionary +Then go throught the elemnts of the array +We subtract this with the given sum +and check if that is there in the array +We also check the edge cases like if there are multiple same elements +Finally we divide the count by 2 +to avoid the same pair getting counted twice +""" + + +def pairs_with_sum(arr, k): + """ + Return the no. of pairs with sum k + + >>> pairs_with_sum([1,5,7,1],6) + 2 + >>> pairs_with_sum([1,1,1,1,1,1,1,1],2) + 28 + >>> pairs_with_sum([1,7,6,2,5,4,3,1,9,8],7) + 4 + """ + d = {} + for i in arr: + if i in d: + d[i]+=1 + else: + d[i] = 1 + ans = 0 + for i in arr: + d[i]-=1 + if k-i in d and d[k-i]!=0: + ans+=d[k-i] + d[i]+=1 + return ans//2 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()