Count distinct pairs with given sum
Given an array arr[] of size N and an integer K, the task is to find the count of distinct pairs in the array whose sum is equal to K.
Examples:
Input: arr[] = { 5, 6, 5, 7, 7, 8 }, K = 13
Output: 2
Explanation:
Pairs with sum K( = 13) are { (arr[0], arr[5]), (arr[1], arr[3]), (arr[1], arr[4]) }, i.e. {(5, 8), (6, 7), (6, 7)}.
Therefore, distinct pairs with sum K( = 13) are { (arr[0], arr[5]), (arr[1], arr[3]) }.
Therefore, the required output is 2.
Input: arr[] = { 2, 6, 7, 1, 8, 3 }, K = 10
Output : 2
Explanation:
Distinct pairs with sum K( = 10) are { (arr[0], arr[4]), (arr[2], arr[5]) }.
Therefore, the required output is 2.
Naive Approach: The simplest approach to solve this problem is to use Two Pointer technique. The idea is to sort the array and remove all consecutive duplicate elements from the given array. Finally, count the pairs in the given array whose sum is equal to K. Follow the steps below to solve the problem:
- Initialize a variable, say cntPairs, to store the count of distinct pairs of the array with sum K.
- Sort the array in increasing order.
- Initialize two variables, say i = 0, j = N – 1 as the index of left and right pointers to traverse the array.
- Traverse the array and check for the following conditions:
- Finally, print the value of cntPairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntDisPairs( int arr[],
int N, int K)
{
int cntPairs = 0;
sort(arr, arr + N);
int i = 0;
int j = N - 1;
while (i < j) {
if (arr[i] + arr[j] == K) {
while (i < j && arr[i] == arr[i + 1]) {
i++;
}
while (i < j && arr[j] == arr[j - 1]) {
j--;
}
cntPairs += 1;
i++;
j--;
}
else if (arr[i] + arr[j] < K) {
i++;
}
else {
j--;
}
}
return cntPairs;
}
int main()
{
int arr[] = { 5, 6, 5, 7, 7, 8 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 13;
cout << cntDisPairs(arr, N, K);
}
|
Java
import java.util.*;
class GFG{
static int cntDisPairs( int arr[],
int N, int K)
{
int cntPairs = 0 ;
Arrays.sort(arr);
int i = 0 ;
int j = N - 1 ;
while (i < j) {
if (arr[i] + arr[j] == K) {
while (i < j && arr[i] == arr[i + 1 ]) {
i++;
}
while (i < j && arr[j] == arr[j - 1 ]) {
j--;
}
cntPairs += 1 ;
i++;
j--;
}
else if (arr[i] + arr[j] < K) {
i++;
}
else {
j--;
}
}
return cntPairs;
}
public static void main(String[] args)
{
int arr[] = { 5 , 6 , 5 , 7 , 7 , 8 };
int N = arr.length;
int K = 13 ;
System.out.print(cntDisPairs(arr, N, K));
}
|
Python3
def cntDisPairs(arr, N, K):
cntPairs = 0
arr = sorted (arr)
i = 0
j = N - 1
while (i < j):
if (arr[i] + arr[j] = = K):
while (i < j and arr[i] = = arr[i + 1 ]):
i + = 1
while (i < j and arr[j] = = arr[j - 1 ]):
j - = 1
cntPairs + = 1
i + = 1
j - = 1
elif (arr[i] + arr[j] < K):
i + = 1
else :
j - = 1
return cntPairs
if __name__ = = '__main__' :
arr = [ 5 , 6 , 5 , 7 , 7 , 8 ]
N = len (arr)
K = 13
print (cntDisPairs(arr, N, K))
|
C#
using System;
class GFG{
static int cntDisPairs( int []arr,
int N, int K)
{
int cntPairs = 0;
Array.Sort(arr);
int i = 0;
int j = N - 1;
while (i < j)
{
if (arr[i] + arr[j] == K)
{
while (i < j && arr[i] == arr[i + 1])
{
i++;
}
while (i < j && arr[j] == arr[j - 1])
{
j--;
}
cntPairs += 1;
i++;
j--;
}
else if (arr[i] + arr[j] < K)
{
i++;
}
else
{
j--;
}
}
return cntPairs;
}
public static void Main(String[] args)
{
int []arr = { 5, 6, 5, 7, 7, 8 };
int N = arr.Length;
int K = 13;
Console.WriteLine(cntDisPairs(arr, N, K));
}
}
|
Javascript
<script>
function cntDisPairs(arr,N , K)
{
var cntPairs = 0;
arr.sort();
var i = 0;
var j = N - 1;
while (i < j) {
if (arr[i] + arr[j] == K) {
while (i < j && arr[i] == arr[i + 1]) {
i++;
}
while (i < j && arr[j] == arr[j - 1]) {
j--;
}
cntPairs += 1;
i++;
j--;
}
else if (arr[i] + arr[j] < K) {
i++;
}
else {
j--;
}
}
return cntPairs;
}
var arr = [ 5, 6, 5, 7, 7, 8 ];
var N = arr.length;
var K = 13;
document.write(cntDisPairs(arr, N, K));
</script>
|
Time Complexity: O(N * log(N))
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using hashing. Follow the steps below to solve the problem:
- Use two sets, one for numbers and one for pairs seen before.
- Traverse through the array and see if (target – arr[i]) is present in set and arr[i] is not present in seen .
- If yes, then add both arr[i] and (target – arr[i]) in seen and add one to count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntDisPairs(vector< int > arr, int target) {
unordered_set< int > set;
unordered_set< int > seen;
int count = 0;
for ( int num : arr) {
if (set.find(target-num) != set.end() && seen.find(num) == seen.end() ) {
count++;
seen.insert(num);
seen.insert(target-num);
}
set.insert(num);
}
return count;
}
int main()
{
vector< int > arr = { 1, 5, 1, 5};
int K = 6;
cout << cntDisPairs(arr, K);
}
|
Java
import java.util.*;
class GFG
{
static int cntDisPairs( int arr[],
int N, int K)
{
int cntPairs = 0 ;
HashMap<Integer,Integer> cntFre = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < N; i++)
{
if (cntFre.containsKey(arr[i]))
cntFre.put(arr[i], cntFre.get(arr[i]) + 1 );
else
cntFre.put(arr[i], 1 );
}
for (Map.Entry<Integer,Integer> it : cntFre.entrySet())
{
int i = it.getKey();
if ( 2 * i == K)
{
if (cntFre.get(i) > 1 )
cntPairs += 2 ;
}
else
{
if (cntFre.containsKey(K - i))
{
cntPairs += 1 ;
}
}
}
cntPairs = cntPairs / 2 ;
return cntPairs;
}
public static void main(String[] args)
{
int arr[] = { 5 , 6 , 5 , 7 , 7 , 8 };
int N = arr.length;
int K = 13 ;
System.out.print(cntDisPairs(arr, N, K));
}
}
|
Python3
def cntDisPairs(arr, N, K):
cntPairs = 0
cntFre = {}
for i in arr:
if i in cntFre:
cntFre[i] + = 1
else :
cntFre[i] = 1
for key, value in cntFre.items():
i = key
if ( 2 * i = = K):
if (cntFre[i] > 1 ):
cntPairs + = 2
else :
if (cntFre[K - i]):
cntPairs + = 1
cntPairs = cntPairs / 2
return cntPairs
arr = [ 5 , 6 , 5 , 7 , 7 , 8 ]
N = len (arr)
K = 13
print ( int (cntDisPairs(arr, N, K)))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int cntDisPairs( int []arr,
int N, int K)
{
int cntPairs = 0;
Dictionary< int , int > cntFre = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (cntFre.ContainsKey(arr[i]))
cntFre[arr[i]] = cntFre[arr[i]] + 1;
else
cntFre.Add(arr[i], 1);
}
foreach (KeyValuePair< int , int > it in cntFre)
{
int i = it.Key;
if (2 * i == K)
{
if (cntFre[i] > 1)
cntPairs += 2;
}
else
{
if (cntFre.ContainsKey(K - i))
{
cntPairs += 1;
}
}
}
cntPairs = cntPairs / 2;
return cntPairs;
}
public static void Main(String[] args)
{
int []arr = { 5, 6, 5, 7, 7, 8 };
int N = arr.Length;
int K = 13;
Console.Write(cntDisPairs(arr, N, K));
}
}
|
Javascript
<script>
function cntDisPairs(arr , N , K) {
var cntPairs = 0;
var cntFre = new Map();
for (i = 0; i < N; i++) {
if (cntFre.has(arr[i]))
cntFre.set(arr[i], cntFre.get(arr[i]) + 1);
else
cntFre.set(arr[i], 1);
}
for ( var it of cntFre) {
var i = it[0];
if (2 * i == K) {
if (cntFre[i] > 1)
cntPairs += 2;
}
else {
if (cntFre.has(K - i)) {
cntPairs += 1;
}
}
}
cntPairs = cntPairs / 2;
return cntPairs;
}
var arr = [ 5, 6, 5, 7, 7, 8 ];
var N = arr.length;
var K = 13;
document.write(cntDisPairs(arr, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
01 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...