Count number of distinct pairs whose sum exists in the given array
Last Updated :
09 Feb, 2023
Given an array of N positive integers. Count the number of pairs whose sum exists in the given array. While repeating pairs will not be counted again. And we can't make a pair using same position element. Eg : (2, 1) and (1, 2) will be considered as only one pair. Please read all examples carefully.
Examples:
Input : arr[] = {1, 2, 3, 5, 10}
Output : 2
Explanation : Here there are two such pairs:
(1 + 2) = 3, (2 + 3) = 5.
Note : Here we can't take pair (5, 5) as
we can see 5 is not coming twice
Input : arr[] = {1, 5, 6, 4, -1, 5}
Output : 4
Explanation : (1 + 5) = 6, (1 + 4) = 5,
(5 + -1) = 4, (6 + -1) = 5
Note : Here (1, 5) comes twice will be
considered as only one pair.
Input : arr[] = {5, 5, 5, 5, 10}
Output : 1
Explanation : (5 + 5) = 10
Note : Here (5, 5) comes twice will be
considered as only one pair.
The idea is to map of pairs to find unique elements. We first store elements and their counts in a map. Then we traverse array elements, for every pair of elements (arr[i], arr[j]), we check if (arr[i] + arr[j]) exists in array. If exists, then we check if it is already counted using map of pairs. If not already counted, then we increment count.
Implementation:
C++
// C++ implementation to find count of unique pairs
// whose sum exists in given array
#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)
{
// Store counts of all elements in map m
// to find pair (arr[i], sum-arr[i])
// because (arr[i]) + (sum - arr[i]) = sum
map<int, int> m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
// To remove duplicate items we use result map
map<pair<int, int>, int> pairs;
int count = 0; // Initialize result
// Consider all pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If sum of current pair exists
if (m[arr[i] + arr[j]] > 0 &&
pairs[{ arr[i], arr[j] }] == 0) {
count++;
}
// Insert current pair both ways to avoid
// duplicates.
pairs[{ arr[i], arr[j] }]++;
pairs[{ arr[j], arr[i] }]++;
}
}
return count;
}
// Driver function to test the above function
int main()
{
int arr[] = { 1, 5, 6, 4, -1, 5, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << getPairsCount(arr, n);
return 0;
}
Java
// Java implementation to find count of unique
// pairs whose sum exists in given array
import java.io.*;
import java.util.*;
class GFG {
public static int getPairsCount(int[] arr, int n)
{
// Store counts of all elements in map m
// to find pair (arr[i], sum-arr[i])
// because (arr[i]) + (sum - arr[i]) = sum
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < n; i++) {
m.put(arr[i], m.getOrDefault(arr[i], 0) + 1);
}
// To remove duplicate items we use result map
Map<Map.Entry<Integer, Integer>, Integer> pairs
= new HashMap<>();
int count = 0; // Initialize result
// Consider all pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If sum of current pair exists
if (m.getOrDefault(arr[i] + arr[j], 0) > 0
&& !pairs.containsKey(
Map.entry(arr[i], arr[j]))) {
count++;
}
// Insert current pair both ways to avoid
// duplicates.
pairs.put(Map.entry(arr[i], arr[j]), 1);
pairs.put(Map.entry(arr[j], arr[i]), 1);
}
}
return count;
}
public static void main(String[] args)
{
int[] arr = { 1, 5, 6, 4, -1, 5, 10 };
int n = arr.length;
System.out.println(getPairsCount(arr, n));
}
}
// This code is contributed by lokesh.
Python3
# Python3 implementation to find count
# of unique pairs whose sum exists in
# given array
# Returns number of pairs in arr[0..n-1]
# with sum equal to 'sum'
def getPairsCount(arr, n):
# Store counts of all elements in map m
# to find pair (arr[i], sum-arr[i])
# because (arr[i]) + (sum - arr[i]) = sum
m = dict()
for i in range(n):
m[arr[i]] = m.get(arr[i], 0) + 1
# To remove duplicate items
# we use result map
pairs1 = dict()
count = 0 # Initialize result
for i in range(n):
for j in range(i + 1, n):
l = arr[i] + arr[j]
tp = (arr[i], arr[j])
if l in m.keys():
if tp not in pairs1.keys():
count += 1
pairs1[(arr[i], arr[j])] = 1
pairs1[(arr[j], arr[i])] = 1
return count
# Driver Code
arr = [1, 5, 6, 4, -1, 5, 10]
n = len(arr)
print(getPairsCount(arr, n))
# This code is contributed by Mohit Kumar
C#
using System;
using System.Collections.Generic;
class GFG {
public static int GetPairsCount(int[] arr, int n)
{
// Store counts of all elements in dictionary m
// to find pair (arr[i], sum-arr[i])
// because (arr[i]) + (sum - arr[i]) = sum
Dictionary<int, int> m = new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (!m.ContainsKey(arr[i])) {
m[arr[i]] = 0;
}
m[arr[i]] += 1;
}
// To remove duplicate items we use result set
HashSet<Tuple<int, int>> pairs = new HashSet<Tuple<int, int>>();
int count = 0; // Initialize result
// Consider all pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If sum of current pair exists
if (m.ContainsKey(arr[i] + arr[j]) &&
m[arr[i] + arr[j]] > 0 &&
!pairs.Contains(new Tuple<int, int>(arr[i], arr[j]))) {
count++;
}
// Insert current pair both ways to avoid
// duplicates.
pairs.Add(new Tuple<int, int>(arr[i], arr[j]));
pairs.Add(new Tuple<int, int>(arr[j], arr[i]));
}
}
return count;
}
public static void Main(string[] args)
{
int[] arr = { 1, 5, 6, 4, -1, 5, 10 };
int n = arr.Length;
Console.WriteLine(GetPairsCount(arr, n));
}
}
JavaScript
// JavaScript implementation to find count of unique
// pairs whose sum exists in given array
function getPairsCount(arr, n) {
// Store counts of all elements in object
// to find pair (arr[i], sum-arr[i])
// because (arr[i]) + (sum - arr[i]) = sum
let m = {};
for (let i = 0; i < n; i++) {
if (m[arr[i]] === undefined) {
m[arr[i]] = 1;
} else {
m[arr[i]]++;
}
}
// To remove duplicate items we use result object
let pairs = {};
let count = 0; // Initialize result
// Consider all pairs
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// If sum of current pair exists
if (m[arr[i] + arr[j]] !== undefined && !(arr[i] in pairs &&
arr[j] in pairs[arr[i]])) {
count++;
}
// Insert current pair both ways to avoid duplicates.
if (!(arr[i] in pairs)) {
pairs[arr[i]] = {};
}
pairs[arr[i]][arr[j]] = 1;
if (!(arr[j] in pairs)) {
pairs[arr[j]] = {};
}
pairs[arr[j]][arr[i]] = 1;
}
}
return count;
}
let arr = [1, 5, 6, 4, -1, 5, 10];
let n = arr.length;
console.log(getPairsCount(arr, n));
// this code is contributed by dnyeshwatdod
Time complexity: O(n^2)
Space complexity: O(n)
Similar Reads
Count of distinct pair sum in given Array Given an array arr[] of size N, the task is to find the total number of unique pair sums possible from the array elements. Examples: Input: arr[] = {6, 1, 4, 3}Output: 5Explanation: All pair possible are {6, 1}, {6, 4}, {6, 3}, {1, 4}, {1, 3}, {4, 3}. Sums of these pairs are 7, 10, 9, 5, 4, 7. So un
4 min read
Given two arrays count all pairs whose sum is an odd number Given two arrays of N and M integers. The task is to find the number of unordered pairs formed of elements from both arrays in such a way that their sum is an odd number. Note: An element can only be one pair.Examples: Input: a[] = {9, 14, 6, 2, 11}, b[] = {8, 4, 7, 20} Output: 3 {9, 20}, {14, 7} an
7 min read
Count number of pairs in array having sum divisible by K | SET 2 Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)I
6 min read
Count number of pairs in array having sum divisible by K | SET 2 Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)I
6 min read
Count of distinct index pair (i, j) such that element sum of First Array is greater Given two arrays a[] and b[], both of size N. The task is to count the number of distinct pairs such that (a[i] + a[j] ) > ( b[i] + b[j] ) subject to condition that (j > i). Examples: Input: N = 5, a[] = {1, 2, 3, 4, 5}, b[] = {2, 5, 6, 1, 9} Output: 1 Explanation: Only one such pair exists an
13 min read
Count distinct pairs from two arrays having same sum of digits Given two arrays arr1[] and arr2[]. The task is to find the total number of distinct pairs(formed by picking 1 element from arr1 and one element from arr2), such that both the elements of the pair have the sum of digits. Note: Pairs occurring more than once must be counted only once. Examples: Input
7 min read