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: 5
Explanation: All pair possible are {6, 1}, {6, 4}, {6, 3}, {1, 4}, {1, 3}, {4, 3}. S
ums of these pairs are 7, 10, 9, 5, 4, 7. So unique sums 7, 10, 9, 5, 4. So answer is 5.
Input: arr[] = {8, 7, 6, 5, 4, 3, 2, 1}
Output: 13
Approach: This problem can be efficiently solved by using unordered_set.
Calculate all possible sum of pairs and store them in an unordered set. This is done to store the store elements in an average time of O(1) with no value repeating.
Algorithm:
- Use nested loops to get all possible sums of elements of the array.
- Store all the possible sums into an unordered_set.
- Total possible unique sums would be equal to the size of unordered_set. So return the size of the unordered set.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count( int arr[], int n)
{
unordered_set< int > s;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
s.insert(arr[i] + arr[j]);
}
}
return s.size();
}
int main()
{
int arr[] = { 6, 1, 4, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << count(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int count( int arr[], int n)
{
Set<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n - 1 ; i++) {
for ( int j = i + 1 ; j < n; j++) {
s.add(arr[i] + arr[j]);
}
}
return s.size();
}
public static void main(String args[])
{
int arr[] = { 6 , 1 , 4 , 3 };
int N = arr.length;
System.out.println(count(arr, N));
}
}
|
Python3
def count(arr, n):
s = set ()
for i in range (n - 1 ):
for j in range (i + 1 , n):
s.add(arr[i] + arr[j])
return int ( len (s))
if __name__ = = '__main__' :
arr = [ 6 , 1 , 4 , 3 ]
N = len (arr)
print (count(arr, N))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int count( int []arr, int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
s.Add(arr[i] + arr[j]);
}
}
return s.Count;
}
static public void Main()
{
int []arr = { 6, 1, 4, 3 };
int N = arr.Length;
Console.WriteLine(count(arr, N));
}
}
|
Javascript
<script>
function count(arr, n) {
let s = new Set();
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
s.add(arr[i] + arr[j]);
}
}
return s.size;
}
let arr = [6, 1, 4, 3];
let N = arr.length;
document.write(count(arr, N));
</script>
|
Time complexity: O(N2)
Auxiliary Space: O(N)
Last Updated :
01 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...