Count distinct pairs with given sum - GeeksforGeeks

28 Dec, 2021
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( = 13) 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: If arr[i] + arr[j] == K: Remove consecutive duplicate array elements and increment the cntPairs by 1. Update i = i + 1 and j = j – 1.If arr[i] + arr[j] < K then update i = i + 1.Otherwise, update j = j – 1.
If arr[i] + arr[j] == K: Remove consecutive duplicate array elements and increment the cntPairs by 1. Update i = i + 1 and j = j – 1.
If arr[i] + arr[j] < K then update i = i + 1.
Otherwise, update j = j – 1.
Finally, print the value of cntPairs.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to count distinct pairs// in array whose sum equal to Kint cntDisPairs(int arr[],                int N, int K){    // Stores count of distinct pairs    // whose sum equal to K    int cntPairs = 0;     // Sort the array    sort(arr, arr + N);     // Stores index of    // the left pointer    int i = 0;     // Stores index of    // the right pointer    int j = N - 1;     // Calculate count of distinct    // pairs whose sum equal to K    while (i < j) {         // If sum of current pair        // is equal to K        if (arr[i] + arr[j] == K) {             // Remove consecutive duplicate            // array elements            while (i < j && arr[i] == arr[i + 1]) {                 // Update i                i++;            }             // Remove consecutive duplicate            // array elements            while (i < j && arr[j] == arr[j - 1]) {                 // Update j                j--;            }             // Update cntPairs            cntPairs += 1;             // Update i            i++;             // Update j            j--;        }         // if sum of current pair        // less than K        else if (arr[i] + arr[j] < K) {             // Update i            i++;        }        else {             // Update j            j--;        }    }    return cntPairs;} // Driver Codeint 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 program to implement// the above approachimport java.util.*; class GFG{ // Function to count distinct pairs// in array whose sum equal to Kstatic int cntDisPairs(int arr[],                int N, int K){    // Stores count of distinct pairs    // whose sum equal to K    int cntPairs = 0;     // Sort the array    Arrays.sort(arr);     // Stores index of    // the left pointer    int i = 0;     // Stores index of    // the right pointer    int j = N - 1;     // Calculate count of distinct    // pairs whose sum equal to K    while (i < j) {         // If sum of current pair        // is equal to K        if (arr[i] + arr[j] == K) {             // Remove consecutive duplicate            // array elements            while (i < j && arr[i] == arr[i + 1]) {                 // Update i                i++;            }             // Remove consecutive duplicate            // array elements            while (i < j && arr[j] == arr[j - 1]) {                 // Update j                j--;            }             // Update cntPairs            cntPairs += 1;             // Update i            i++;             // Update j            j--;        }         // if sum of current pair        // less than K        else if (arr[i] + arr[j] < K) {             // Update i            i++;        }        else {             // Update j            j--;        }    }    return cntPairs;} // Driver Codepublic 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));}    // This code is contributed by 29AjayKumar
# Python3 program to implement# the above approach # Function to count distinct pairs# in array whose sum equal to Kdef cntDisPairs(arr, N, K):         # Stores count of distinct pairs    # whose sum equal to K    cntPairs = 0     # Sort the array    arr = sorted(arr)     # Stores index of    # the left pointer    i = 0     # Stores index of    # the right pointer    j = N - 1     # Calculate count of distinct    # pairs whose sum equal to K    while (i < j):         # If sum of current pair        # is equal to K        if (arr[i] + arr[j] == K):             # Remove consecutive duplicate            # array elements            while (i < j and arr[i] == arr[i + 1]):                 # Update i                i += 1             # Remove consecutive duplicate            # array elements            while (i < j and arr[j] == arr[j - 1]):                 # Update j                j -= 1             # Update cntPairs            cntPairs += 1             # Update i            i += 1             # Update j            j -= 1         # If sum of current pair        # less than K        elif (arr[i] + arr[j] < K):             # Update i            i += 1        else:             # Update j            j -= 1                 return cntPairs # Driver Codeif __name__ == '__main__':         arr = [ 5, 6, 5, 7, 7, 8 ]    N = len(arr)    K = 13         print(cntDisPairs(arr, N, K)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;class GFG{ // Function to count distinct pairs// in array whose sum equal to Kstatic int cntDisPairs(int []arr,                       int N, int K){         // Stores count of distinct pairs    // whose sum equal to K    int cntPairs = 0;     // Sort the array    Array.Sort(arr);     // Stores index of    // the left pointer    int i = 0;     // Stores index of    // the right pointer    int j = N - 1;     // Calculate count of distinct    // pairs whose sum equal to K    while (i < j)    {                 // If sum of current pair        // is equal to K        if (arr[i] + arr[j] == K)        {                         // Remove consecutive duplicate            // array elements            while (i < j && arr[i] == arr[i + 1])            {                                 // Update i                i++;            }             // Remove consecutive duplicate            // array elements            while (i < j && arr[j] == arr[j - 1])            {                                 // Update j                j--;            }             // Update cntPairs            cntPairs += 1;             // Update i            i++;             // Update j            j--;        }         // If sum of current pair        // less than K        else if (arr[i] + arr[j] < K)        {                         // Update i            i++;        }        else        {                         // Update j            j--;        }    }    return cntPairs;} // Driver Codepublic 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));}}   // This code is contributed by jana_sayantan
<script> // javascript program to implement// the above approach  // Function to count distinct pairs// in array whose sum equal to Kfunction cntDisPairs(arr,N , K){    // Stores count of distinct pairs    // whose sum equal to K    var cntPairs = 0;     // Sort the array    arr.sort();     // Stores index of    // the left pointer    var i = 0;     // Stores index of    // the right pointer    var j = N - 1;     // Calculate count of distinct    // pairs whose sum equal to K    while (i < j) {         // If sum of current pair        // is equal to K        if (arr[i] + arr[j] == K) {             // Remove consecutive duplicate            // array elements            while (i < j && arr[i] == arr[i + 1]) {                 // Update i                i++;            }             // Remove consecutive duplicate            // array elements            while (i < j && arr[j] == arr[j - 1]) {                 // Update j                j--;            }             // Update cntPairs            cntPairs += 1;             // Update i            i++;             // Update j            j--;        }         // if sum of current pair        // less than K        else if (arr[i] + arr[j] < K) {             // Update i            i++;        }        else {             // Update j            j--;        }    }    return cntPairs;} // Driver Code var arr = [ 5, 6, 5, 7, 7, 8 ];var N = arr.length;var K = 13;document.write(cntDisPairs(arr, N, K)); // This code contributed by shikhasingrajput </script>
2
 
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++
Java
Python3
C#
Javascript
// C++ program to implement#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 program to implement// the above approachimport java.util.*; class GFG{ // Function to count distinct pairs// in array whose sum equal to Kstatic int cntDisPairs(int arr[],                int N, int K){       // Stores count of distinct pairs    // whose sum equal to K    int cntPairs = 0;     // Store frequency of each distinct    // element of the array    HashMap<Integer,Integer> cntFre = new HashMap<Integer,Integer>();     for (int i = 0; i < N; i++)    {         // Update frequency        // of arr[i]        if(cntFre.containsKey(arr[i]))            cntFre.put(arr[i], cntFre.get(arr[i]) + 1);                 else            cntFre.put(arr[i], 1);    }     // Traverse the map    for (Map.Entry<Integer,Integer> it : cntFre.entrySet())    {         // Stores key value        // of the map        int i = it.getKey();         // If i is the half of K        if (2 * i == K)        {             // If frequency of i            // greater than  1            if (cntFre.get(i) > 1)                cntPairs += 2;        }         else        {            if (cntFre.containsKey(K - i))            {                 // Update cntPairs                cntPairs += 1;            }        }    }     // Update cntPairs    cntPairs = cntPairs / 2;    return cntPairs;} // Driver Codepublic 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));}} // This code  is contributed by shikhasingrajput
# Python3 program to implement# the above approach # Function to count distinct pairs# in array whose sum equal to Kdef cntDisPairs(arr, N, K):       # Stores count of distinct pairs    # whose sum equal to K    cntPairs = 0     # Store frequency of each distinct    # element of the array    cntFre = {}     for i in arr:                 # Update frequency        # of arr[i]        if i in cntFre:            cntFre[i] += 1        else:            cntFre[i] = 1     # Traverse the map    for key, value in cntFre.items():         # Stores key value        # of the map        i = key         # If i is the half of K        if (2 * i == K):                         # If frequency of i            # greater than  1            if (cntFre[i] > 1):                cntPairs += 2        else:            if (cntFre[K - i]):                 # Update cntPairs                cntPairs += 1     # Update cntPairs    cntPairs = cntPairs / 2     return cntPairs # Driver Codearr = [ 5, 6, 5, 7, 7, 8 ]N = len(arr)K = 13           print(int(cntDisPairs(arr, N, K))) # This code is contributed by Dharanendra L V
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{   // Function to count distinct pairs  // in array whose sum equal to K  static int cntDisPairs(int []arr,                         int N, int K)  {     // Stores count of distinct pairs    // whose sum equal to K    int cntPairs = 0;     // Store frequency of each distinct    // element of the array    Dictionary<int,int> cntFre = new Dictionary<int,int>();     for (int i = 0; i < N; i++)    {       // Update frequency      // of arr[i]      if(cntFre.ContainsKey(arr[i]))        cntFre[arr[i]] = cntFre[arr[i]] + 1;       else        cntFre.Add(arr[i], 1);    }     // Traverse the map    foreach (KeyValuePair<int,int> it in cntFre)    {       // Stores key value      // of the map      int i = it.Key;       // If i is the half of K      if (2 * i == K)      {         // If frequency of i        // greater than  1        if (cntFre[i] > 1)          cntPairs += 2;      }       else      {        if (cntFre.ContainsKey(K - i))        {           // Update cntPairs          cntPairs += 1;        }      }    }     // Update cntPairs    cntPairs = cntPairs / 2;    return cntPairs;  }   // Driver Code  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));  }} // This code is contributed by 29AjayKumar
<script>// javascript program to implement// the above approach     // Function to count distinct pairs    // in array whose sum equal to K    function cntDisPairs(arr , N , K) {         // Stores count of distinct pairs        // whose sum equal to K        var cntPairs = 0;         // Store frequency of each distinct        // element of the array        var cntFre =new  Map();         for (i = 0; i < N; i++) {             // Update frequency            // of arr[i]            if (cntFre.has(arr[i]))                cntFre.set(arr[i], cntFre.get(arr[i]) + 1);             else                cntFre.set(arr[i], 1);        }         // Traverse the map        for (var it of cntFre) {             // Stores key value            // of the map            var i = it[0];             // If i is the half of K            if (2 * i == K) {                 // If frequency of i                // greater than 1                if (cntFre[i] > 1)                    cntPairs += 2;            }             else {                if (cntFre.has(K - i)) {                     // Update cntPairs                    cntPairs += 1;                }            }        }         // Update cntPairs        cntPairs = cntPairs / 2;        return cntPairs;    }     // Driver Code             var arr = [ 5, 6, 5, 7, 7, 8 ];        var N = arr.length;        var K = 13;        document.write(cntDisPairs(arr, N, K)); // This code is contributed by umadevi9616</script>
2
 
Time Complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
jana_sayantan
shikhasingrajput
dharanendralv23
umadevi9616
lovishpuri
frequency-counting
Arrays
Hash
Mathematical
Searching
Arrays
Searching
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Sort string of characters