Print all pairs in an unsorted array with equal sum in C++


In this problem, we have an unsorted array and we have to print all pairs within this array that have an equal sum.

Let’s take an example to understand the problem −

Input: array = [12, 13, 20, 5]
Output: [12, 13] and [20, 5] have sum 25.

To solve this problem, we will have to find pairs of the same sum. For this, we will check pairs for the same sum. And to avoid duplicate pairs, we will use the map.

For this, we will need two maps, one to store all sum pairs and their sum and others to store all sum and their corresponding pairs.

So, Map1 → key = pairs; value → sum

Map2 → key = sum integer; value → vector of pair

Now, print all values that have the same sum value.

Example

Program to illustrate the above logic −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findEqualSumPairs(int A[], int n){
   map<int, vector<pair<int, int> > >map1;
   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]);
         map1[A[i] + A[j]].push_back(p);
      }
   }
   for (auto value = map1.begin(); value != map1.end(); value++) {
      if (value->second.size() > 1) {
         for (int i = 0; i < value->second.size(); i++) {
            cout<<"[ "<<value->second[i].first<<", "<<value->second[i].second<<"] ";
         }
         cout<<"have sum : "<<value->first<<endl;
      }
   }
}
int main() {
   int A[] = { 6, 4, 12, 10, 22,11, 8, 2 };
   int n = sizeof(A) / sizeof(A[0]);
   cout<<"Pairs with same sum are : \n";
   findEqualSumPairs(A, n);
   return 0;
}

Output

Pairs with same sum are −

[ 6, 4] [ 8, 2] have sum : 10
[ 4, 8] [ 10, 2] have sum : 12
[ 6, 8] [ 4, 10] [ 12, 2] have sum : 14
[ 6, 10] [ 4, 12] have sum : 16
[ 6, 12] [ 10, 8] have sum : 18

Updated on: 22-Jan-2020

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements