Print all pairs in an unsorted array with equal sum
Last Updated :
15 Feb, 2023
Given an unsorted array A[]. The task is to print all unique pairs in the unsorted array with equal sum.
Note: Print the result in the format as shown in the below examples.
Examples:
Input: A[] = { 6, 4, 12, 10, 22, 54, 32, 42, 21, 11}
Output:
Pairs : ( 4, 12) ( 6, 10) have sum : 16
Pairs : ( 10, 22) ( 21, 11) have sum : 32
Pairs : ( 12, 21) ( 22, 11) have sum : 33
Pairs : ( 22, 21) ( 32, 11) have sum : 43
Pairs : ( 32, 21) ( 42, 11) have sum : 53
Pairs : ( 12, 42) ( 22, 32) have sum : 54
Pairs : ( 10, 54) ( 22, 42) have sum : 64
Input:A[]= { 4, 23, 65, 67, 24, 12, 86}
Output:
Pairs : ( 4, 86) ( 23, 67) have sum : 90
The idea is to use map in C++ STL for avoiding duplicate pairs of elements.
- Create a map with key as pair of integer and value as integer to store all unique pairs of elements and their corresponding sum.
- Traverse the array and generate all possible pairs and store the pairs and their corresponding sum on the first map.
- Create a second map with key as integer and value as a vector of pair to store a list of all pairs of elements with a corresponding sum.
- Finally, traverse the second map, and for a sum with more than one pair, print all pairs and then the corresponding sum in a format as shown in the above example.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void pairWithEqualSum( int A[], int n)
{
map< int , vector<pair< int , int > > > mp;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
pair< int , int > p = make_pair(A[i], A[j]);
mp[A[i] + A[j]].push_back(p);
}
}
for ( auto itr = mp.begin(); itr != mp.end(); itr++) {
if (itr->second.size() > 1) {
cout << "Pairs : " ;
for ( int i = 0; i < itr->second.size(); i++) {
cout << "( " << itr->second[i].first << ", "
<< itr->second[i].second << ") " ;
}
cout << " have sum : " << itr->first << endl;
}
}
}
int main()
{
int A[]
= { 6, 4, 12, 10, 22, 54, 32, 42, 21, 11, 8, 2 };
int n = sizeof (A) / sizeof (A[0]);
pairWithEqualSum(A, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static class pair {
int first, second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static void pairWithEqualSum( int A[], int n)
{
Map<Integer, Vector<pair> > mp = new HashMap<>();
for ( int i = 0 ; i < n - 1 ; i++) {
for ( int j = i + 1 ; j < n; j++) {
pair p = new pair(A[i], A[j]);
Vector<pair> pp = new Vector<pair>();
if (mp.containsKey(A[i] + A[j]))
pp.addAll(mp.get(A[i] + A[j]));
pp.add(p);
mp.put(A[i] + A[j], pp);
}
}
for (Map.Entry<Integer, Vector<pair> > itr :
mp.entrySet()) {
if (itr.getValue().size() > 1 ) {
System.out.print( "Pairs : " );
for ( int i = 0 ; i < itr.getValue().size();
i++) {
System.out.print(
"( " + itr.getValue().get(i).first
+ ", "
+ itr.getValue().get(i).second
+ ") " );
}
System.out.print(
" have sum : " + itr.getKey() + "\n" );
}
}
}
public static void main(String[] args)
{
int A[] = { 6 , 4 , 12 , 10 , 22 , 54 ,
32 , 42 , 21 , 11 , 8 , 2 };
int n = A.length;
pairWithEqualSum(A, n);
}
}
|
Python3
def pairWithEqualSum(A, n):
mp = {}
for i in range (n):
for j in range (i + 1 , n):
if A[i] + A[j] in mp:
mp[A[i] + A[j]].append((A[i], A[j]))
else :
mp[A[i] + A[j]] = [(A[i], A[j])]
for itr in mp:
if len (mp[itr]) > 1 :
print ( "Pairs : " , end = "")
for i in range ( 0 , len (mp[itr])):
print ( "(" , mp[itr][i][ 0 ], "," ,
mp[itr][i][ 1 ], ")" , end = " " )
print ( "have sum :" , itr)
if __name__ = = "__main__" :
A = [ 6 , 4 , 12 , 10 , 22 , 54 ,
32 , 42 , 21 , 11 , 8 , 2 ]
n = len (A)
pairWithEqualSum(A, n)
|
C#
using System;
using System.Collections.Generic;
class GFG {
class pair {
public int first, second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static void pairWithEqualSum( int [] A, int n)
{
Dictionary< int , List<pair> > mp
= new Dictionary< int , List<pair> >();
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
pair p = new pair(A[i], A[j]);
List<pair> pp = new List<pair>();
if (mp.ContainsKey(A[i] + A[j]))
pp = AddAll(mp[A[i] + A[j]]);
pp.Add(p);
if (mp.ContainsKey(A[i] + A[j]))
mp[A[i] + A[j]] = pp;
else
mp.Add(A[i] + A[j], pp);
}
}
foreach (KeyValuePair< int , List<pair> > itr in mp)
{
if (itr.Value.Count > 1) {
Console.Write( "Pairs : " );
for ( int i = 0; i < itr.Value.Count; i++) {
Console.Write(
"( " + itr.Value[i].first + ", "
+ itr.Value[i].second + ") " );
}
Console.Write( " have sum : " + itr.Key
+ "\n" );
}
}
}
static List<pair> AddAll(List<pair> list)
{
List<pair> l = new List<pair>();
foreach (pair p in list) l.Add(p);
return l;
}
public static void Main(String[] args)
{
int [] A = { 6, 4, 12, 10, 22, 54,
32, 42, 21, 11, 8, 2 };
int n = A.Length;
pairWithEqualSum(A, n);
}
}
|
Javascript
function pairWithEqualSum(A, n) {
let mp = new Map();
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
let p = [A[i], A[j]];
let sum = A[i] + A[j];
if (mp.has(sum)) {
let arr = mp.get(sum);
arr.push(p);
mp.set(sum, arr);
} else {
let temp = []
temp.push(p);
mp.set(sum, temp);
}
}
}
for (let [key, value] of mp) {
if (value.length > 1) {
console.log( "Pairs: " );
for (let i = 0; i < value.length; i++) {
console.log( "(" + value[i][0] + ", " + value[i][1] + ") " );
}
console.log( " have sum : " + key);
}
}
}
let A = [6, 4, 12, 10, 22, 54, 32, 42, 21, 11, 8, 2];
let n = A.length;
pairWithEqualSum(A, n);
|
Output
Pairs : ( 6, 4) ( 8, 2) have sum : 10
Pairs : ( 4, 8) ( 10, 2) have sum : 12
Pairs : ( 6, 8) ( 4, 10) ( 12, 2) have sum : 14
Pairs : ( 6, 10) ( 4, 12) have sum : 16
Pairs : ( 6, 12) ( 10, 8) have sum : 18
Pairs : ( 12, 11) ( 21, 2) have sum : 23
Pairs : ( 10, 22) ( 21, 11) have sum : 32
Pairs : ( 12, 21) ( 22, 11) have sum : 33
Pairs : ( 12, 22) ( 32, 2) have sum : 34
Pairs : ( 22, 21) ( 32, 11) have sum : 43
Pairs : ( 12, 32) ( 42, 2) have sum : 44
Pairs : ( 32, 21) ( 42, 11) have sum : 53
Pairs : ( 12, 42) ( 22, 32) have sum : 54
Pairs : ( 10, 54) ( 22, 42) have sum : 64
Time Complexity: O(n2log(n)), as nested loops are used
Auxiliary Space: O(n), as extra space of size n is used to create a map
Implementation: Another implementation of the same above approach using one Single map.
C++
#include <bits/stdc++.h>
using namespace std;
void findPairs(vector< int > arr)
{
map< int , int > mp;
int sum = 0, element = 0;
for ( int i = 0; i < arr.size(); i++) {
for ( int j = i + 1; j < arr.size(); j++) {
sum = arr[i] + arr[j];
if (mp.count(sum)) {
element = mp[sum];
cout << "Pairs:(" << arr[i] << "," << arr[j]
<< ") (" << element << ","
<< "(" << sum - element << ")"
<< ") have sum:" << sum << endl;
}
else {
mp[sum] = arr[i];
}
}
}
}
int main()
{
vector< int > arr
= { 6, 4, 12, 10, 22, 54, 32, 42, 21, 11, 8, 2 };
findPairs(arr);
}
|
Java
import java.io.*;
import java.util.HashMap;
import java.util.Map;
class GFG{
public void findPairs( int arr[]){
Map<Integer,
Integer> map = new HashMap<Integer,
Integer>();
int sum = 0 , element = 0 ;
for ( int i = 0 ; i < arr.length; i++)
{
for ( int j = i + 1 ; j < arr.length; j++)
{
sum = arr[i] + arr[j];
if (map.get(sum) != null )
{
element = map.get(sum);
System.out.println( "Pairs:(" + arr[i] +
"," + arr[j] + ") (" +
element + "," +
(sum - element) +
") have sum:" + sum);
}
else
{
map.put(sum, arr[i]);
}
}
}
}
public static void main(String[] args)
{
int arr[] = { 6 , 4 , 12 , 10 , 22 , 54 ,
32 , 42 , 21 , 11 , 8 , 2 };
GFG obj = new GFG();
obj.findPairs(arr);
}
}
|
Python3
class GFG :
def findPairs( self , arr) :
map = dict ()
sum = 0
element = 0
i = 0
while (i < len (arr)) :
j = i + 1
while (j < len (arr)) :
sum = arr[i] + arr[j]
if ( map .get( sum ) ! = None ) :
element = map .get( sum )
print ( "Pairs:(" + str (arr[i]) + "," + str (arr[j]) + ") (" + str (element) + "," + str (( sum - element)) + ") have sum:" + str ( sum ))
else :
map [ sum ] = arr[i]
j + = 1
i + = 1
@staticmethod
def main( args) :
arr = [ 6 , 4 , 12 , 10 , 22 , 54 , 32 , 42 , 21 , 11 , 8 , 2 ]
obj = GFG()
obj.findPairs(arr)
if __name__ = = "__main__" :
GFG.main([])
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void findPairs( int [] arr){
Dictionary< int , int > map = new Dictionary< int , int >();
int sum = 0, element = 0;
for ( int i = 0; i < arr.Length; i++)
{
for ( int j = i + 1; j < arr.Length; j++)
{
sum = arr[i] + arr[j];
if (map.ContainsKey(sum))
{
element = map[sum];
Console.WriteLine( "Pairs:(" + arr[i] +
"," + arr[j] + ") (" +
element + "," +
(sum - element) +
") have sum:" + sum);
}
else
{
map[sum] = arr[i];
}
}
}
}
public static void Main(String[] args)
{
int [] arr = {6, 4, 12, 10, 22, 54,
32, 42, 21, 11, 8, 2};
findPairs(arr);
}
}
|
Javascript
function findPairs(arr) {
let mp = {};
let sum = 0, element = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
sum = arr[i] + arr[j];
if (mp[sum]) {
element = mp[sum];
document.write( "Pairs:(" + arr[i] + "," + arr[j]
+ ") (" + (element) + ","
+ "(" + (sum - element) + ")"
+ ") have sum:" + sum);
}
else {
mp[sum] = arr[i];
}
}
}
}
let arr = [6, 4, 12, 10, 22, 54, 32, 42, 21, 11, 8, 2];
findPairs(arr);
|
Output
Pairs:(4,12) (6,(10)) have sum:16
Pairs:(4,10) (6,(8)) have sum:14
Pairs:(12,2) (6,(8)) have sum:14
Pairs:(10,8) (6,(12)) have sum:18
Pairs:(10,2) (4,(8)) have sum:12
Pairs:(22,32) (12,(42)) have sum:54
Pairs:(22,42) (10,(54)) have sum:64
Pairs:(22,11) (12,(21)) have sum:33
Pairs:(32,11) (22,(21)) have sum:43
Pairs:(32,2) (12,(22)) have sum:34
Pairs:(42,11) (32,(21)) have sum:53
Pairs:(42,2) (12,(32)) have sum:44
Pairs:(21,11) (10,(22)) have sum:32
Pairs:(21,2) (12,(11)) have sum:23
Pairs:(8,2) (6,(4)) have sum:10
Complexity Analysis:
- Time Complexity: O(n2logn), as nested loops are used
- Auxiliary Space: O(n), as extra space of size n is used to create a Hashmap
Similar Reads
Find all pairs with a given sum in two unsorted arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X. Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3 Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output:
13 min read
Pairs with sum greater than 0 in an array
Given an array arr[] of size N, the task is to find the number of distinct pairs in the array whose sum is > 0. Examples: Input: arr[] = { 3, -2, 1 } Output: 2 Explanation: There are two pairs of elements in the array {3, -2}, {3, 1} whose sum is positive. Input: arr[] = { -1, -1, -1, 0 } Output:
5 min read
Find the largest pair sum in an unsorted array
Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
10 min read
2 Sum - Count Pairs with given Sum in Sorted Array
Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target. Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outp
9 min read
Print all repeating adjacent pairs in sorted order from an array
Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order. Examples: Input: arr[] = {1, 2, 5, 1, 2}Output:1 2Explanation
7 min read
Printing pairs in an Array
Given a pile of n pairs of elements in array arr[], containing 2n elements, we have to print with the following conditions follow: If pair exists of the elements then print it. Two elements form a pair if they have same valueElse do not print the unpaired elementsExamples: Input: n = 3, arr[] = {2,
9 min read
Split an array into two equal Sum subarrays
Given an array of integers greater than zero, find if it is possible to split it in two subarrays (without reordering the elements), such that the sum of the two subarrays is the same. Print the two subarrays. Examples : Input : Arr[] = { 1 , 2 , 3 , 4 , 5 , 5 } Output : { 1 2 3 4 } { 5 , 5 } Input
15 min read
Find the sum of all possible pairs in an array of N elements
Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.Examples: Input: arr[] = {1, 2} Output: 12 All va
7 min read
Count all distinct pairs with product equal to K
Given an integer array arr[] of size N and a positive integer K, the task is to count all the distinct pairs in the array with product equal to K.Examples: Input: arr[] = {1, 5, 3, 4, 2}, K = 3 Output: 1 Explanation: There is only one pair (1, 3) with product = K = 3. Input: arr[] = {1, 2, 16, 4, 4}
15+ min read
Find all the pairs with given sum in a BST | Set 2
Given a Binary Search Tree and an integer sum, the task is to find all the pairs from the tree whose sum is equal to the given integer sum. We have discussed a similar problem in this post. Examples: Input: 2 / \ 1 6 / \ 5 7 / 3 \ 4 sum = 8 Output: 1 7 2 6 3 5 Input: 2 / \ 1 3 \ 4 sum = 5 Output: 1
15+ min read