Challenge: Find Two Pairs in an Array such that a+b = c+d

If you are given an array, can you find two pairs such that their sum is equal? A solution is placed in the "solution" section to help you, but we would suggest you try to solve it on your own first.

Problem Statement

In this problem, you have to implement the findPair() function to find two pairs or 4 elements (a,b,c,d) in an array, such that,

a+b=c+da+b = c+d

You only have to find first two pairs in the array which satisfies the above condition. An illustration is also provided for your understanding.

Function Prototype:

String findPair(int[] arr);

Here, arr is an Integer array.

Output:

It returns a String containing two pairs, (a,b) and (c,d), which satisfies a+b = c+d.

Sample Input

arr = {3, 4, 7, 1, 12, 9}

Sample Output

"{4,12}{7,9}"

Explanation

4,12,7 and 9 follow the above condition, as 4+12 = 7+9. There are so many other possible pairs in the sample input that satisfy the above condition, but for this problem, we only have to find one of them.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.