Find four elements a , b , c and d in an array such that a + b = c + d | Java Program to find four different elements a , b , c and d of array such that a + b = c + d ; Class to represent a pair ; 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 ; Testing program
import java . io . * ; import java . util . * ; class ArrayElements { class pair { int first , second ; pair ( int f , int s ) { first = f ; second = s ; } } ; boolean findPairs ( int arr [ ] ) { HashMap < Integer , pair > map = new HashMap < Integer , pair > ( ) ; int n = arr . length ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int sum = arr [ i ] + arr [ j ] ; if ( ! map . containsKey ( sum ) ) map . put ( sum , new pair ( i , j ) ) ; else { pair p = map . get ( sum ) ; System . out . println ( " ( " + arr [ p . first ] + " , ▁ " + arr [ p . second ] + " ) ▁ and ▁ ( " + arr [ i ] + " , ▁ " + arr [ j ] + " ) " ) ; return true ; } } } return false ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 4 , 7 , 1 , 2 , 9 , 8 } ; ArrayElements a = new ArrayElements ( ) ; a . findPairs ( arr ) ; } }