Find four elements a , b , c and d in an array such that a + b = c + d | 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 ) ; Create an empty Hash to store mapping from sum to pair indexes ; Traverse through all possible pairs of arr [ ] ; If sum of current pair is not in hash , then store it and continue to next pair ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findPairs ( int arr [ ] , int n ) { map < int , pair < int , int > > Hash ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int sum = arr [ i ] + arr [ j ] ; if ( Hash . find ( sum ) == Hash . end ( ) ) Hash [ sum ] = make_pair ( i , j ) ; else { pair < int , int > pp = Hash [ sum ] ; cout << " ( " << arr [ pp . first ] << " , ▁ " << arr [ pp . second ] << " ) ▁ and ▁ ( " << arr [ i ] << " , ▁ " << arr [ j ] << " ) n " ; return true ; } } } cout << " No ▁ pairs ▁ found " ; return false ; } int main ( ) { int arr [ ] = { 3 , 4 , 7 , 1 , 2 , 9 , 8 } ; int n = sizeof arr / sizeof arr [ 0 ] ; findPairs ( arr , n ) ; return 0 ; }