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.
- Finally, print the value of cntPairs.
Below is the implementation of the above approach:
C++
// 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 K int 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 Code 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
// Java program to implement // the above approach import java.util.*; 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 ; // 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 Code 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)); } // This code is contributed by 29AjayKumar |
Python3
# Python3 program to implement # the above approach # Function to count distinct pairs # in array whose sum equal to K def 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 Code if __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#
// C# program to implement // the above approach using System; 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; // 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 Code 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)); } } // This code is contributed by jana_sayantan |
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:
- Initialize a variable, say cntPairs, to store the count of distinct pairs of the array whose sum is equal to K.
- Initialize a map, say cntFre, to store the frequency of each distinct element of the array.
- Traverse the array and store the frequency of each distinct elements of the array in the map.
- Traverse the map using key value of the map as i and check if the key K – i present in the map or not. If found to be true then increment cntPairs by 1.
- Finally, print the value of cntPairs.
Below is the implementation of the above approach:
C++
// 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 K 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 unordered_map< int , int > cntFre; for ( int i = 0; i < N; i++) { // Update frequency // of arr[i] cntFre[arr[i]]++; } // Traverse the map for ( auto it : cntFre) { // Stores key value // of the map int i = it.first; // 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 Code 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
// Java program to implement // the above approach import java.util.*; 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 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 Code 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)); } } // This code is contributed by shikhasingrajput |
Python3
# Python3 program to implement # the above approach # Function to count distinct pairs # in array whose sum equal to K def 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 Code arr = [ 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#
// C# program to implement // the above approach using 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 |
2
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.