Count pairs with given sum
Given an array of N integers, and a number sum, the task is to 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
Explanation: Pairs with sum 6 are (1, 5) and (7, -1).Input: arr[] = {1, 5, 7, -1, 5}, sum = 6
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).Input: arr[] = {1, 1, 1, 1}, sum = 2
Output: 6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).Input: arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, sum = 11
Output: 9
Explanation: Pairs with sum 11 are (10, 1), (10, 1), (10, 1), (12, -1), (10, 1), (10, 1), (10, 1), (7, 4), (6, 5).
Naive Approach:
- 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.
- This can be achieved by nested loops.
Illustration:
Given arr[] = {1, 5, 7, -1}, sum = 6
count = 0
- First Iteration : For index = 0
{1, 5, 7, -1}, pair = (1, 5), count = 1- Second Iteration : For index = 1
{1, 5, 7, -1}, count = 1- Third Iteration : For index = 2
{1, 5, 7, -1}, count = 2Hence output is 2
Follow the steps below to solve the given problem:
- Initialize the count variable with 0 which stores the result.
- Iterate arr and if the sum of ith and jth [i + 1…..n – 1] element is equal to sum i.e. arr[i] + arr[j] == sum, then increment the count variable.
- Return the count.
Below is the implementation of the above approach.
C++
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount( int arr[], int n, int sum) { int count = 0; // Initialize result // Consider all possible pairs and check their sums for ( int i = 0; i < n; i++) for ( int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count; } // Driver function to test the above function 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; } // This code is contributed by Aditya Kumar (adityakumar129) |
C
// C implementation of simple method to find count of // pairs with given sum. #include <stdio.h> // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount( int arr[], int n, int sum) { int count = 0; // Initialize result // Consider all possible pairs and check their sums for ( int i = 0; i < n; i++) for ( int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count; } // Driver function to test the above function int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof (arr) / sizeof (arr[0]); int sum = 6; printf ( "Count of pairs is %d" , getPairsCount(arr, n, sum)); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
Java
// Java implementation of simple method to find count of // pairs with given sum. public class find { public static void main(String args[]) { int [] arr = { 1 , 5 , 7 , - 1 , 5 }; int sum = 6 ; getPairsCount(arr, sum); } // Prints number of pairs in arr[0..n-1] with sum equal // to 'sum' public static void getPairsCount( int [] arr, int sum) { int count = 0 ; // Initialize result // Consider all possible pairs and check their sums for ( int i = 0 ; i < arr.length; i++) for ( int j = i + 1 ; j < arr.length; j++) if ((arr[i] + arr[j]) == sum) count++; System.out.printf( "Count of pairs is %d" , count); } } // This code is contributed by Aditya Kumar (adityakumar129) |
Python3
# Python3 implementation of simple method # to find count of pairs with given sum. # Returns number of pairs in arr[0..n-1] # with sum equal to 'sum' def getPairsCount(arr, n, sum ): count = 0 # Initialize result # Consider all possible pairs # and check their sums for i in range ( 0 , n): for j in range (i + 1 , n): if arr[i] + arr[j] = = sum : count + = 1 return count # Driver function arr = [ 1 , 5 , 7 , - 1 , 5 ] n = len (arr) sum = 6 print ( "Count of pairs is" , getPairsCount(arr, n, sum )) # This code is contributed by Smitha Dinesh Semwal |
C#
// C# implementation of simple // method to find count of // pairs with given sum. using System; class GFG { public static void getPairsCount( int [] arr, int sum) { int count = 0; // Initialize result // Consider all possible pairs // and check their sums for ( int i = 0; i < arr.Length; i++) for ( int j = i + 1; j < arr.Length; j++) if ((arr[i] + arr[j]) == sum) count++; Console.WriteLine( "Count of pairs is " + count); } // Driver Code static public void Main() { int [] arr = { 1, 5, 7, -1, 5 }; int sum = 6; getPairsCount(arr, sum); } } // This code is contributed // by Sach_Code |
PHP
<?php // PHP implementation of simple // method to find count of // pairs with given sum. // Returns number of pairs in // arr[0..n-1] with sum equal // to 'sum' function getPairsCount( $arr , $n , $sum ) { // Initialize result $count = 0; // Consider all possible pairs // and check their sums for ( $i = 0; $i < $n ; $i ++) for ( $j = $i + 1; $j < $n ; $j ++) if ( $arr [ $i ] + $arr [ $j ] == $sum ) $count ++; return $count ; } // Driver Code $arr = array (1, 5, 7, -1, 5) ; $n = sizeof( $arr ); $sum = 6; echo "Count of pairs is " , getPairsCount( $arr , $n , $sum ); // This code is contributed by nitin mittal. ?> |
Javascript
<script> // Javascript implementation of simple method to find count of // pairs with given sum. // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' function getPairsCount(arr, n, sum) { let count = 0; // Initialize result // Consider all possible pairs and check their sums for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count; } // Driver function to test the above function let arr = [ 1, 5, 7, -1, 5 ]; let n = arr.length; let sum = 6; document.write( "Count of pairs is " + getPairsCount(arr, n, sum)); // This code is contributed by Mayank Tyagi </script> |
Count of pairs is 3
Time Complexity: O(n2), traversing the array for each element
Auxiliary Space: O(1)
Count pairs with given sum using Binary Search
This approach is based on the following idea:
- If the array is sorted then for each array element arr[i], find the number of pairs by finding all the values (sum – arr[i]) which are situated after ith index.
- This can be achieved using Binary Search.
Illustration:
Given arr[] = {1, 5, 7, -1}, sum = 6
Array after sorting: arr[] = {-1, 1, 5, 7}
count = 0At index = 0: val = sum – arr[0] = 6 – (-1) = 7
count = count + upperBound(1, 3, 7) – lowerBound(1, 3, 7)
count = 1At index = 1: val = sum – arr[1] = 6 – 1 = 5
count = count + upperBound(2, 3, 5) – lowerBound(2, 3, 5)
count = 2At index = 2: val = sum – arr[2] = 6 – 5 = 1
count = count + upperBound(3, 3, 1) – lowerBound(3, 3, 1)
count = 2Number of pairs = 2
Follow the steps below to solve the given problem:
- Sort the array arr[] in increasing order.
- Loop from i = 0 to N-1.
- Find the index of the first element having value same or just greater than (sum – arr[i]) using lower bound.
- Find the index of the first element having value just greater than (sum – arr[i]) using upper bound.
- The gap between these two indices is the number of elements with value same as (sum – arr[i]).
- Add this with the final count of pairs.
- Return the final count after the iteration is over.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the count of pairs int getPairsCount( int arr[], int n, int k) { sort(arr, arr + n); int x = 0, c = 0, y, z; for ( int i = 0; i < n - 1; i++) { x = k - arr[i]; // Lower bound from i+1 int y = lower_bound(arr + i + 1, arr + n, x) - arr; // Upper bound from i+1 int z = upper_bound(arr + i + 1, arr + n, x) - arr; c = c + z - y; } return c; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof (arr) / sizeof (arr[0]); int k = 6; // Function call cout << "Count of pairs is " << getPairsCount(arr, n, k); return 0; } |
Java
// Java code for the above approach import java.io.*; import java.util.*; class GFG { // lowerBound implementation public static int lowerBound( int [] arr, int start, int end, int key) { while (start < end) { int mid = start + (end - start) / 2 ; if (arr[mid] < key) { start = mid + 1 ; } else { end = mid; } } return start; } // upperBound implementation public static int upperBound( int [] arr, int start, int end, int key) { while (start < end) { int mid = start + (end - start) / 2 ; if (arr[mid] <= key) { start = mid + 1 ; } else { end = mid; } } return start; } // Function to find the count of pairs public static int getPairsCount( int [] arr, int n, int k) { Arrays.sort(arr); int c = 0 ; for ( int i = 0 ; i < n - 1 ; i++) { int x = k - arr[i]; int y = lowerBound(arr, i + 1 , n, x); int z = upperBound(arr, i + 1 , n, x); c = c + z - y; } return c; } public static void main(String[] args) { int [] arr = { 1 , 5 , 7 , - 1 , 5 }; int n = arr.length; int k = 6 ; // Function call System.out.println( "Count of pairs is " + getPairsCount(arr, n, k)); } } // This code is contributed by lokeshmvs21. |
Python3
# Python code to implement the approach import bisect # Function to find the count of pairs def getPairsCount(arr, n, k): arr.sort() x, c = 0 , 0 for i in range (n - 1 ): x = k - arr[i] # Lower bound from i+1 y = bisect.bisect_left(arr, x, i + 1 , n) # Upper bound from i+1 z = bisect.bisect(arr, x, i + 1 , n) c = c + z - y return c # Driver function arr = [ 1 , 5 , 7 , - 1 , 5 ] n = len (arr) k = 6 # Function call print ( "Count of pairs is" , getPairsCount(arr, n, k)) # This code is contributed by Pushpesh Raj |
C#
// C# code for the above approach using System; using System.Collections; public class GFG { // lowerBound implementation public static int lowerBound( int [] arr, int start, int end, int key) { while (start < end) { int mid = start + (end - start) / 2; if (arr[mid] < key) { start = mid + 1; } else { end = mid; } } return start; } // upperBound implementation public static int upperBound( int [] arr, int start, int end, int key) { while (start < end) { int mid = start + (end - start) / 2; if (arr[mid] <= key) { start = mid + 1; } else { end = mid; } } return start; } // Function to find the count of pairs public static int getPairsCount( int [] arr, int n, int k) { Array.Sort(arr); int c = 0; for ( int i = 0; i < n - 1; i++) { int x = k - arr[i]; int y = lowerBound(arr, i + 1, n, x); int z = upperBound(arr, i + 1, n, x); c = c + z - y; } return c; } static public void Main() { // Code int [] arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int k = 6; // Function call Console.WriteLine( "Count of pairs is " + getPairsCount(arr, n, k)); } } // This code is contributed by lokesh. |
Count of pairs is 3
Time Complexity: O(n * log(n) ), applying binary search on each element
Auxiliary Space: O(1)
Count pairs with given sum using Hashing
This approach is based on the following idea:
- Check the frequency of sum – arr[i] in the arr
- This can be achieved using Hashing.
Illustration:
Given arr[] = {1, 5, 7, -1}, sum = 6
- Store the frequency of every element:
freq[arr[i]] = freq[arr[i]] + 1
freq[1] : 1
freq[5] : 1
freq[7] : 1
freq[-1] : 1
- Initialise a variable count with 0 to find the required count of pairs
- At index = 0: freq[sum – arr[0]] = freq[6 – 1] = freq[5] = 1
count = 1- At index = 1: freq[sum – arr[1]] = freq[6 – 5] = freq[1] = 1
count = 2- At index = 2: freq[sum – arr[2]] = freq[6 – 7] = freq[-1] = 1
count = 3- At index = 3: freq[sum – arr[3]] = freq[6 – (-1)] = freq[7] = 1
count = 4- The above also contains repeated pairs from front and last, i.e. pair (a, b) and (b, a) are considered as different pairs till now.
Therefore, we will reduce the count by half to determine the count of unique pairs.
count = count / 2 = 2- Therefore, required Number of pairs with given sum = 2
Follow the steps below to solve the given problem:
- Create a map to store the 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 the second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide the count by 2 and return.
Below is the implementation of the above idea :
C++
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount( int arr[], int n, int sum) { unordered_map< int , int > m; // Store counts of all elements in map m for ( int i = 0; i < n; i++) m[arr[i]]++; int twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for ( int i = 0; i < n; i++) { twice_count += m[sum - arr[i]]; // if (arr[i], arr[i]) pair satisfies the condition, // then we need to ensure that the count is // decreased by one such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2; } // Driver function to test the above function 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; } |
Java
/* Java implementation of simple method to find count of pairs with given sum*/ import java.util.HashMap; class Test { static int arr[] = new int [] { 1 , 5 , 7 , - 1 , 5 }; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' static int getPairsCount( int n, int sum) { HashMap<Integer, Integer> hm = new HashMap<>(); // Store counts of all elements in map hm for ( int i = 0 ; i < n; i++) { // initializing value to 0, if key not found if (!hm.containsKey(arr[i])) hm.put(arr[i], 0 ); hm.put(arr[i], hm.get(arr[i]) + 1 ); } int twice_count = 0 ; // iterate through each element and increment the // count (Notice that every pair is counted twice) for ( int i = 0 ; i < n; i++) { if (hm.get(sum - arr[i]) != null ) twice_count += hm.get(sum - arr[i]); // if (arr[i], arr[i]) pair satisfies the // condition, then we need to ensure that the // count is decreased by one such that the // (arr[i], arr[i]) pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2 ; } // Driver method to test the above function public static void main(String[] args) { int sum = 6 ; System.out.println( "Count of pairs is " + getPairsCount(arr.length, sum)); } } // This code is contributed by Gaurav Miglani |
Python3
# Python 3 implementation of simple method # to find count of pairs with given sum. import sys # Returns number of pairs in arr[0..n-1] # with sum equal to 'sum' def getPairsCount(arr, n, sum ): m = [ 0 ] * 1000 # Store counts of all elements in map m for i in range ( 0 , n): m[arr[i]] + = 1 twice_count = 0 # Iterate through each element and increment # the count (Notice that every pair is # counted twice) for i in range ( 0 , n): twice_count + = m[ sum - arr[i]] # if (arr[i], arr[i]) pair satisfies the # condition, then we need to ensure that # the count is decreased by one such # that the (arr[i], arr[i]) pair is not # considered if ( sum - arr[i] = = arr[i]): twice_count - = 1 # return the half of twice_count return int (twice_count / 2 ) # Driver function arr = [ 1 , 5 , 7 , - 1 , 5 ] n = len (arr) sum = 6 print ( "Count of pairs is" , getPairsCount(arr, n, sum )) # This code is contributed by # Smitha Dinesh Semwal |
C#
// C# implementation of simple method to // find count of pairs with given sum using System; using System.Collections.Generic; class GFG { public static int [] arr = new int [] { 1, 5, 7, -1, 5 }; // Returns number of pairs in arr[0..n-1] // with sum equal to 'sum' public static int getPairsCount( int n, int sum) { Dictionary< int , int > hm = new Dictionary< int , int >(); // Store counts of all elements // in map hm for ( int i = 0; i < n; i++) { // initializing value to 0, // if key not found if (!hm.ContainsKey(arr[i])) { hm[arr[i]] = 0; } hm[arr[i]] = hm[arr[i]] + 1; } int twice_count = 0; // iterate through each element and // increment the count (Notice that // every pair is counted twice) for ( int i = 0; i < n; i++) { if (hm[sum - arr[i]] != 0) { twice_count += hm[sum - arr[i]]; } // if (arr[i], arr[i]) pair satisfies // the condition, then we need to ensure // that the count is decreased by one // such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) { twice_count--; } } // return the half of twice_count return twice_count / 2; } // Driver Code public static void Main( string [] args) { int sum = 6; Console.WriteLine( "Count of pairs is " + getPairsCount(arr.Length, sum)); } } // This code is contributed by Shrikant13 |
Javascript
<script> /* javascript implementation of simple method to find count of pairs with given sum*/ var arr = [ 1, 5, 7, -1, 5 ]; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' function getPairsCount(n , sum) { var hm = new Map(); // Store counts of all elements in map hm for ( var i = 0; i < n; i++) { // initializing value to 0, if key not found if (!hm.has(arr[i])) hm.set(arr[i], 0); hm.set(arr[i], hm.get(arr[i]) + 1); } var twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for (i = 0; i < n; i++) { if (hm.get(sum - arr[i]) != null ) twice_count += hm.get(sum - arr[i]); // if (arr[i], arr[i]) pair satisfies the // condition, then we need to ensure that the // count is decreased by one such that the // (arr[i], arr[i]) pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2; } // Driver method to test the above function var sum = 6; document.write( "Count of pairs is " + getPairsCount(arr.length, sum)); // This code is contributed by umadevi9616 </script> |
Count of pairs is 3
Time Complexity: O(n), to iterate over the array
Auxiliary Space: O(n), to make a map of size n
Count pairs with given sum using Hashing in Single loop
This approach is based on the following idea:
- The idea is to solve in single loop.
- Check the frequency of sum – arr[i] in the arr
- This can be achieved using Hashing.
Illustration:
Given arr[] = {1, 5, 7, -1}, sum = 6
count = 0
At index = 0: freq[sum – arr[0]] = freq[6 – 1] = freq[5] = 0
count = 0
freq[arr[0]] = freq[1] = 1At index = 1: freq[sum – arr[1]] = freq[6 – 5] = freq[1] = 1
count = 1
freq[arr[1]] = freq[5] = 1At index = 2: freq[sum – arr[2]] = freq[6 – 7] = freq[-1] = 0
count = 1
freq[arr[2]] = freq[7] = 1At index = 3: freq[sum – arr[3]] = freq[6 – (-1)] = freq[7] = 1
count = 2
freq[arr[3]] = freq[-1] = 1count = 2
Number of pairs = 2
Follow the steps below to solve the given problem:
- Create a map to store the frequency of each number in the array.
- Check if (sum – arr[i]) is present in the map, if present then increment the count variable by its frequency.
- After traversal is over, return the count.
Below is the implementation of the above idea :
C++
// C++ implementation of simple method to // find count of pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount( int arr[], int n, int k) { unordered_map< int , int > m; int count = 0; for ( int i = 0; i < n; i++) { if (m.find(k - arr[i]) != m.end()) { count += m[k - arr[i]]; } m[arr[i]]++; } return count; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof (arr) / sizeof (arr[0]); int sum = 6; // Function Call cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0; } |
Java
// Java implementation of simple method to find count of // pairs with given sum. import java.util.*; class GFG { // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' static int getPairsCount( int arr[], int n, int k) { HashMap<Integer, Integer> m = new HashMap<>(); int count = 0 ; for ( int i = 0 ; i < n; i++) { if (m.containsKey(k - arr[i])) { count += m.get(k - arr[i]); } if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1 ); } else { m.put(arr[i], 1 ); } } return count; } // Driver function to test the above function public static void main(String[] args) { int arr[] = { 1 , 5 , 7 , - 1 , 5 }; int n = arr.length; int sum = 6 ; System.out.print( "Count of pairs is " + getPairsCount(arr, n, sum)); } } // This code is contributed by umadevi9616 |
Python3
# Python implementation of simple method to find count of # pairs with given sum. # Returns number of pairs in arr[0..n-1] with sum equal to 'sum' def getPairsCount(arr, n, sum ): unordered_map = {} count = 0 for i in range (n): if sum - arr[i] in unordered_map: count + = unordered_map[ sum - arr[i]] if arr[i] in unordered_map: unordered_map[arr[i]] + = 1 else : unordered_map[arr[i]] = 1 return count # Driver code arr = [ 1 , 5 , 7 , - 1 , 5 ] n = len (arr) sum = 6 print ( 'Count of pairs is' , getPairsCount(arr, n, sum )) # This code is contributed by Manish Thapa |
C#
// C# implementation of simple method to find count of // pairs with given sum. using System; using System.Collections.Generic; public class GFG { // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' static int getPairsCount( int [] arr, int n, int k) { Dictionary< int , int > m = new Dictionary< int , int >(); int count = 0; for ( int i = 0; i < n; i++) { if (m.ContainsKey(k - arr[i])) { count += m[k - arr[i]]; } if (m.ContainsKey(arr[i])) { m[arr[i]] = m[arr[i]] + 1; } else { m.Add(arr[i], 1); } } return count; } // Driver function to test the above function public static void Main(String[] args) { int [] arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int sum = 6; Console.Write( "Count of pairs is " + getPairsCount(arr, n, sum)); } } // This code is contributed by umadevi9616 |
Javascript
<script> // javascript implementation of simple method to find count of // pairs with given sum. // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' function getPairsCount(arr , n , k) { var m = new Map(); var count = 0; for ( var i = 0; i < n; i++) { if (m.has(k - arr[i])) { count += m.get(k - arr[i]); } if (m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1); } else { m.set(arr[i], 1); } } return count; } // Driver function to test the above function var arr = [ 1, 5, 7, -1, 5 ]; var n = arr.length; var sum = 6; document.write( "Count of pairs is " + getPairsCount(arr, n, sum)); // This code is contributed by umadevi9616 </script> |
Count of pairs is 3
Time Complexity: O(n), to iterate over the array
Auxiliary Space: O(n), to make a map of size n
Please Login to comment...