 Open in App
Not now

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

• Difficulty Level : Medium
• Last Updated : 23 Jan, 2023

Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then print any of them.

Example:

```Input:   {3, 4, 7, 1, 2, 9, 8}
Output:  (3, 8) and (4, 7)
Explanation: 3+8 = 4+7

Input:   {3, 4, 7, 1, 12, 9};
Output:  (4, 12) and (7, 9)
Explanation: 4+12 = 7+9

Input:  {65, 30, 7, 90, 1, 9, 8};
Output:  No pairs found```

Expected Time Complexity: O(n2)

Recommended Practice

A Simple Solution is to run four loops to generate all possible quadruples of the array elements. For every quadruple (a, b, c, d), check if (a+b) = (c+d). The time complexity of this solution is O(n4).
An Efficient Solution can solve this problem in O(n2) time. The idea is to use hashing. We use sum as key and pair as the value in the hash table.

```Loop i = 0 to n-1 :
Loop j = i + 1 to n-1 :
calculate sum
If in hash table any index already exist
Then print (i, j) and previous pair
from hash table
Else update hash table
EndLoop;
EndLoop;```

Below are implementations of the above idea. In the below implementation, the map is used instead of a hash. The time complexity of map insert and search is actually O(Log n) instead of O(1). So below implementation is O(n2 Log n).

## C++

 `// Find four different elements a,b,c and d of array such that ` `// a+b = c+d ` `#include ` `using` `namespace` `std; `   `bool` `findPairs(``int` `arr[], ``int` `n) ` `{ ` `    ``// Create an empty Hash to store mapping from sum to ` `    ``// pair indexes ` `    ``map<``int``, pair<``int``, ``int``> > Hash; `   `    ``// Traverse through all possible pairs of arr[] ` `    ``for` `(``int` `i = 0; i < n; ++i) ` `    ``{ ` `        ``for` `(``int` `j = i + 1; j < n; ++j) ` `        ``{ ` `            ``// If sum of current pair is not in hash, ` `            ``// then store it and continue to next pair ` `            ``int` `sum = arr[i] + arr[j]; ` `            ``if` `(Hash.find(sum) == Hash.end()) ` `                ``Hash[sum] = make_pair(i, j); `   `            ``else` `// Else (Sum already present in hash) ` `            ``{ ` `                ``// Find previous pair ` `                ``pair<``int``, ``int``> pp = Hash[sum];``// pp->previous pair `   `                ``// Since array elements are distinct, we don't ` `                ``// need to check if any element is common among pairs ` `                ``cout << ``"("` `<< arr[pp.first] << ``", "` `<< arr[pp.second] ` `                    ``<< ``") and ("` `<< arr[i] << ``", "` `<< arr[j] << ``")n"``; ` `                ``return` `true``; ` `            ``} ` `        ``} ` `    ``} `   `    ``cout << ``"No pairs found"``; ` `    ``return` `false``; ` `} `   `// Driver program ` `int` `main() ` `{ ` `    ``int` `arr[] = {3, 4, 7, 1, 2, 9, 8}; ` `    ``int` `n = ``sizeof` `arr / ``sizeof` `arr; ` `    ``findPairs(arr, n); ` `    ``return` `0; ` `} `

## Java

 `// Java Program to find four different elements a,b,c and d of` `// array such that a+b = c+d` `import` `java.io.*;` `import` `java.util.*;`   `class` `ArrayElements` `{` `    ``// Class to represent a pair` `    ``class` `pair` `    ``{` `        ``int` `first, second;` `        ``pair(``int` `f,``int` `s)` `        ``{` `            ``first = f; second = s;` `        ``}` `    ``};`   `    ``boolean` `findPairs(``int` `arr[])` `    ``{` `        ``// Create an empty Hash to store mapping from sum to` `        ``// pair indexes` `        ``HashMap map = ``new` `HashMap();` `        ``int` `n=arr.length;`   `        ``// Traverse through all possible pairs of arr[]` `        ``for` `(``int` `i=``0``; i

## Python3

 `# Python Program to find four different elements a,b,c and d of` `# array such that a+b = c+d`   `# function to find a, b, c, d such that` `# (a + b) = (c + d)`     `def` `find_pair_of_sum(arr: ``list``, n: ``int``):` `    ``map` `=` `{}`   `    ``for` `i ``in` `range``(n):` `        ``for` `j ``in` `range``(i``+``1``, n):` `            ``sum` `=` `arr[i] ``+` `arr[j]`   `            ``if` `sum` `in` `map``:` `                ``print``(f``"{map[sum]} and ({arr[i]}, {arr[j]})"``)` `                ``return` `            ``else``:` `                ``map``[``sum``] ``=` `(arr[i], arr[j])`     `# Driver code` `if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``3``, ``4``, ``7``, ``1``, ``2``, ``9``, ``8``]` `    ``n ``=` `len``(arr)` `    ``find_pair_of_sum(arr, n)`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `// C# Program to find four different elements a,b,c and d of ` `// array such that a+b = c+d `   `public` `class` `ArrayElements` `{` `    ``// Class to represent a pair ` `    ``public` `class` `pair` `    ``{` `        ``private` `readonly` `ArrayElements outerInstance;`   `        ``public` `int` `first, second;` `        ``public` `pair(ArrayElements outerInstance, ``int` `f, ``int` `s)` `        ``{` `            ``this``.outerInstance = outerInstance;` `            ``first = f;` `            ``second = s;` `        ``}` `    ``}`   `    ``public` `virtual` `bool` `findPairs(``int``[] arr)` `    ``{` `        ``// Create an empty Hash to store mapping from sum to ` `        ``// pair indexes ` `        ``Dictionary<``int``, pair> map = ``new` `Dictionary<``int``, pair>();` `        ``int` `n = arr.Length;`   `        ``// Traverse through all possible pairs of arr[] ` `        ``for` `(``int` `i = 0; i < n; ++i)` `        ``{` `            ``for` `(``int` `j = i + 1; j < n; ++j)` `            ``{` `                ``// If sum of current pair is not in hash, ` `                ``// then store it and continue to next pair ` `                ``int` `sum = arr[i] + arr[j];` `                ``if` `(!map.ContainsKey(sum))` `                ``{` `                    ``map[sum] = ``new` `pair(``this``, i,j);` `                ``}`   `                ``else` `// Else (Sum already present in hash)` `                ``{` `                    ``// Find previous pair ` `                    ``pair p = map[sum];`   `                    ``// Since array elements are distinct, we don't ` `                    ``// need to check if any element is common among pairs ` `                    ``Console.WriteLine(``"("` `+ arr[p.first] + ``", "` `+ arr[p.second] + ``") and ("` `+ arr[i] + ``", "` `+ arr[j] + ``")"``);` `                    ``return` `true``;` `                ``}` `            ``}` `        ``}` `        ``return` `false``;` `    ``}`   `    ``// Testing program ` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int``[] arr = ``new` `int``[] {3, 4, 7, 1, 2, 9, 8};` `        ``ArrayElements a = ``new` `ArrayElements();` `        ``a.findPairs(arr);` `    ``}` `}`   `// This code is contributed by Shrikant13`

## Javascript

 ``

Output:

`(3, 8) and (4, 7)`

Time Complexity : O(n2 logn)

Auxiliary Space: O(n)

Thanks to Gaurav Ahirwar for suggesting above solutions.
Exercise:
1) Extend the above solution with duplicates allowed in array.
2) Further extend the solution to print all quadruples in output instead of just one. And all quadruples should be printed  in lexicographical order (smaller values before greater ones). Assume we have two solutions S1 and S2.

```S1 : a1 b1 c1 d1 ( these are values of indices in the array )
S2 : a2 b2 c2 d2

S1 is lexicographically smaller than S2 if
a1 < a2 OR
a1 = a2 AND b1 < b2 OR
a1 = a2 AND b1 = b2 AND c1 < c2 OR
a1 = a2 AND b1 = b2 AND c1 = c2 AND d1 < d2 ```

See this for solution of exercise.

This article is contributed by Aarti_Rathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.