Skip to content

Commit 3c6068e

Browse files
author
Tidimatso Anthony
authored
Update pairs_with_given_sum.py
Dictionary Usage: We use a dictionary seen to keep track of the number of times each number has appeared so far. For each number num in the array, we calculate its complement (req_sum - num). If this complement has been seen before, then it means there are pairs that sum up to req_sum, and we add the count of such complements to our count. Efficiency: This approach processes each element of the array exactly once and performs operations in constant time for each element. Thus, the time complexity is 𝑂 ( 𝑛 ) O(n), where 𝑛 n is the number of elements in the array. Readability: The code is more straightforward and easier to understand compared to generating combinations. It leverages hash maps for efficient lookups and counting.
1 parent f16d38f commit 3c6068e

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

data_structures/arrays/pairs_with_given_sum.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,33 @@
77
https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
88
"""
99

10-
from itertools import combinations
11-
12-
13-
def pairs_with_sum(arr: list, req_sum: int) -> int:
10+
def pairs_with_sum(arr: list[int], req_sum: int) -> int:
1411
"""
15-
Return the no. of pairs with sum "sum"
12+
Return the number of pairs with sum equal to req_sum.
13+
1614
>>> pairs_with_sum([1, 5, 7, 1], 6)
1715
2
1816
>>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2)
1917
28
2018
>>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7)
2119
4
2220
"""
23-
return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])
24-
21+
count = 0
22+
seen = {}
23+
24+
for num in arr:
25+
complement = req_sum - num
26+
if complement in seen:
27+
count += seen[complement]
28+
29+
if num in seen:
30+
seen[num] += 1
31+
else:
32+
seen[num] = 1
33+
34+
return count
2535

2636
if __name__ == "__main__":
2737
from doctest import testmod
28-
2938
testmod()
39+

0 commit comments

Comments
 (0)