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++
// 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 functionint 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.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 program is contributed by Jyotsna |
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 functionarr = [1, 5, 7, -1, 5]n = len(arr)sum = 6print("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.?> |
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++
// 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 functionint 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 ofpairs 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 functionarr = [1, 5, 7, -1, 5]n = len(arr)sum = 6print("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 sumusing 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 |
Count of pairs is 3
This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
Recommended Posts:
- Given an array of pairs, find all symmetric pairs in it
- Count pairs from two sorted arrays whose sum is equal to a given value x
- Count pairs from two linked lists whose sum is equal to a given value
- Count number of distinct pairs whose sum exists in the given array
- Count pairs from two sorted matrices with given sum
- Given two arrays count all pairs whose sum is an odd number
- Count pairs with given sum | Set 2
- Maximum Count of pairs having equal Sum based on the given conditions
- Count of replacements required to make the sum of all Pairs of given type from the Array equal
- Count distinct pairs with given sum
- Sum of absolute differences of pairs from the given array that satisfy the given condition
- Find the maximum cost of an array of pairs choosing at most K pairs
- Count pairs in a sorted array whose sum is less than x
- Count pairs in array whose sum is divisible by 4
- Count number of pairs in array having sum divisible by K | SET 2
- Count pairs with set bits sum equal to K
- Count distinct pairs from two arrays having same sum of digits
- Count of pairs in an array whose sum is a perfect square
- Count pairs in array whose sum is divisible by K
- Maximum count of pairs which generate the same sum

