TheAlgorithms / Python

All Algorithms implemented in Python
https://the-algorithms.com/
MIT License
184.64k stars 44.37k forks source link

Update pairs_with_given_sum.py #11549

Closed tidianthony closed 3 weeks ago

tidianthony commented 3 weeks ago

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.

Describe your change:

Checklist: