C++ Program to Count pairs with given sum
Last Updated :
15 Feb, 2023
Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’.
Examples:
Input : arr[] = {1, 5, 7, -1},
sum = 6
Output : 2
Pairs with sum 6 are (1, 5) and (7, -1)
Input : arr[] = {1, 5, 7, -1, 5},
sum = 6
Output : 3
Pairs with sum 6 are (1, 5), (7, -1) &
(1, 5)
Input : arr[] = {1, 1, 1, 1},
sum = 2
Output : 6
There are 3! pairs with sum 2.
Input : arr[] = {10, 12, 10, 15, -1, 7, 6,
5, 4, 2, 1, 1, 1},
sum = 11
Output : 9
Expected time complexity O(n)
Naive Solution – A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum.
C++
#include <bits/stdc++.h>
using namespace std;
int getPairsCount( int arr[], int n, int sum)
{
int count = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
count++;
return count;
}
int main()
{
int arr[] = { 1, 5, 7, -1, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, sum);
return 0;
}
|
Output
Count of pairs is 3
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient solution –
A better solution is possible in O(n) time. Below is the Algorithm –
- Create a map to store frequency of each number in the array. (Single traversal is required)
- In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly.
- After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return.
Below is the implementation of above idea :
C++
#include <bits/stdc++.h>
using namespace std;
int getPairsCount( int arr[], int n, int sum)
{
unordered_map< int , int > m;
for ( int i = 0; i < n; i++)
m[arr[i]]++;
int twice_count = 0;
for ( int i = 0; i < n; i++) {
twice_count += m[sum - arr[i]];
if (sum - arr[i] == arr[i])
twice_count--;
}
return twice_count / 2;
}
int main()
{
int arr[] = { 1, 5, 7, -1, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, sum);
return 0;
}
|
Output
Count of pairs is 3
Time Complexity: O(n)
Auxiliary Space: O(n)
The extra space is used to store the elements in the map.
Please refer complete article on Count pairs with given sum for more details!
Share your thoughts in the comments
Please Login to comment...