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

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(n^{2})

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(n^{4}).

An** Efficient Solution** can solve this problem in O(n^{2}) 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(n^{2} Log n).

## C++

`// Find four different elements a,b,c and d of array such that` `// a+b = c+d` `#include<bits/stdc++.h>` `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[0];` ` ` `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<Integer,pair> map = ` `new` `HashMap<Integer,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.put(sum,` `new` `pair(i,j));` ` ` `else` `// Else (Sum already present in hash)` ` ` `{` ` ` `// Find previous pair` ` ` `pair p = map.get(sum);` ` ` `// Since array elements are distinct, we don't` ` ` `// need to check if any element is common among pairs` ` ` `System.out.println(` `"("` `+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[] = {` `3` `, ` `4` `, ` `7` `, ` `1` `, ` `2` `, ` `9` `, ` `8` `};` ` ` `ArrayElements a = ` `new` `ArrayElements();` ` ` `a.findPairs(arr);` ` ` `}` `}` `// This code is contributed by Aakash Hasija` |

## 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

`<script>` `// Find four different elements a,b,c and d of array such that` `// a+b = c+d` `function` `findPairs(arr, n) {` ` ` `// Create an empty Hash to store mapping from sum to` ` ` `// pair indexes` ` ` `let Hash = ` `new` `Map();` ` ` `// Traverse through all possible pairs of arr[]` ` ` `for` `(let i = 0; i < n; ++i) {` ` ` `for` `(let j = i + 1; j < n; ++j) {` ` ` `// If sum of current pair is not in hash,` ` ` `// then store it and continue to next pair` ` ` `let sum = arr[i] + arr[j];` ` ` `if` `(!Hash.has(sum))` ` ` `Hash.set(sum, [i, j]);` ` ` `else` `// Else (Sum already present in hash)` ` ` `{` ` ` `// Find previous pair` ` ` `let pp = Hash.get(sum);` `// pp->previous pair` ` ` `// Since array elements are distinct, we don't` ` ` `// need to check if any element is common among pairs` ` ` `document.write(` `"("` `+ arr[pp[0]] + ` `", "` `+ arr[pp[1]] + ` `") and ("` `+ arr[i] + ` `", "` `+ arr[j] + ` `")"` `);` ` ` `return` `true` `;` ` ` `}` ` ` `}` ` ` `}` ` ` `document.write(` `"No pairs found"` `);` ` ` `return` `false` `;` `}` `// Driver program` `let arr = [3, 4, 7, 1, 2, 9, 8];` `let n = arr.length` `findPairs(arr, n);` `</script>` |

**Output:**

(3, 8) and (4, 7)

**Time Complexity : **O(n^{2 }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 int the array ) S2 : a2 b2 c2 d2 S1 is lexicographically smaller than S2 iff 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.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.**Related Article :**

Find all pairs (a,b) and (c,d) in array which satisfy ab = cd

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above