Count Pairs with the Given Sum
- Shreyas Naphad
- Jul 24, 2024
- 1 min read
In this article, we will solve the problem of counting the number of pairs in an array that sum up to a given target value.
Problem Statement: Given an array of integers and a target sum, write a function to count the number of pairs of integers in the array whose sum is equal to the target sum.
Example:
Input: arr = [1, 5, 7, 4, 2], target_sum = 6
Output: 2
Explanation: The pairs with sum 6 are (1, 5) and (4, 2).
Solution:
To solve this problem we can use a hash map to store the frequencies of elements we have seen so far. We will iterate through the array and for each element, check if the complement (target sum - current element) exists in the hash map. If it does, we add the frequency of the complement to our count of pairs.
Steps to Solve:
1. Initialize a hash map to store frequencies of elements.
2. Initialize a variable to count the pairs.
3. Iterate through the array:
o For each element, calculate its complement with respect to the target sum.
o If the complement exists in the hash map, add its frequency to the count of pairs.
o Update the frequency of the current element in the hash map.
4. Return the count of pairs.
Time Complexity: O(N)
Space Complexity: O(N)
Commenti