# Find four elements a, b, c and d in an array such that a+b = c+d in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of integers. Our task is to find four distinct integers as two pairs like (a, b) and (c, d), such that a+b = c+d. If there are multiple answers, then print only one. Suppose the array elements are like: A = [7, 5, 9, 3, 6, 4, 2], then pairs can be (7, 3) and (6, 4)

Here we will use the hashing technique. We use the sum as key as pair as the value in the hash table. We have to follow these steps to solve this problem.

• For i in range 0 to n – 1, do
• for j in range i + 1 to n – 1, do
• find the sum
• If the hash table has the sum already, then print the previous pair and the current pair
• Otherwise, update the hash table.

## Example

Live Demo

#include<iostream>
#include<map>
using namespace std;
bool getTwoPairs(int arr[], int n) {
map<int, pair<int, int> > hash_table;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int sum = arr[i] + arr[j];
if (hash_table.find(sum) == hash_table.end())
hash_table[sum] = make_pair(i, j);
else {
pair<int, int> pp = hash_table[sum];
cout << "(" << arr[pp.first] << " + " << arr[pp.second] << ") = (" << arr[i] << " + " << arr[j] << ")";
return true;
}
}
}
cout << "No pairs found";
return false;
}
int main() {
int arr[] = {7, 5, 9, 3, 6, 4, 2};
int n = sizeof arr / sizeof arr;
cout << "The pairs are: ";
getTwoPairs(arr, n);
}

## Output

The pairs are: (7 + 4) = (5 + 6)