# 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 array element. For every quadruple (a, b, c, d), check if (a+b) = (c+d). 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 value in 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 above idea. In below implementation, map is used instead of hash. 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/C++

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

## Python

`# 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` `findPairs(arr, n):` `# Create an empty hashmap to store mapping` `# from sum to pair indexes` `Hash` `=` `{}` `# Traverse through all possible pairs of arr[]` `for` `i ` `in` `range` `(n ` `-` `1` `):` ` ` `for` `j ` `in` `range` `(i ` `+` `1` `, n):` ` ` `sum` `=` `arr[i] ` `+` `arr[j]` ` ` `# Sum already present in hash` ` ` `if` `sum` `in` `Hash` `.keys():` ` ` `# print previous pair and current` ` ` `prev ` `=` `Hash` `.get(` `sum` `)` ` ` `print` `(` `str` `(prev) ` `+` `" and (%d, %d)"` ` ` `%` `(arr[i], arr[j])) ` ` ` `return` `True` ` ` `else` `:` ` ` `# sum is not in hash` ` ` `# store it and continue to next pair` ` ` `Hash` `[` `sum` `] ` `=` `(arr[i], arr[j])` `return` `False` `# driver program` `arr ` `=` `[` `3` `, ` `4` `, ` `7` `, ` `1` `, ` `2` `, ` `9` `, ` `8` `]` `n ` `=` `len` `(arr)` `findPairs(arr, n)` `# This code is contributed by Aditi Sharma` |

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

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 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.**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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend **live classes **with experts, please refer **DSA Live Classes for Working Professionals **and **Competitive Programming Live for Students**.