Java Program for Count pairs with given sum
Last Updated :
15 Feb, 2023
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.
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
OutputCount 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 :
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
OutputCount of pairs is 3
Time Complexity: O(n)
Auxiliary Space: O(n)
The extra space is used to store the elements in the map.
Please refer complete article on Count pairs with given sum for more details!
Similar Reads
Java Program for Number of pairs with maximum sum Write a java program for a given array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j.Example: Input : arr[] = {1, 1, 1, 2, 2, 2}Output: 3Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the pai
4 min read
Java Program to Count triplets with sum smaller than a given value Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples:Â Â Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input
4 min read
Java Program to Find Sum of Array Elements Given an array of integers. Write a Java Program to find the sum of the elements of the array. Examples: Input : arr[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : arr[] = {15, 12, 13, 10} Output : 50 15 + 12 + 13 + 10 = 50 An array is a data structure that contains a group of elements. Typically th
3 min read
Java Program for Pairs such that one is a power multiple of other We are given an array A[] of n-elements and a positive integer k(other than 1). Now you have find the number of pairs Ai, Aj such that Ai = Aj*(kx) where x is an integer. Given that (k?1). Note: (Ai, Aj) and (Aj, Ai) must be count once. Examples: Input : A[] = {3, 6, 4, 2}, k = 2 Output : 2 Explanat
6 min read
Python Program for Count pairs with given sum 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
3 min read