Find two non | Java program to find two non - overlapping pairs having equal sum in an Array ; Declare a pair ; Function to find two non - overlapping pairs with same sum in an array ; first create an empty map key -> which is sum of a pair of elements in the array value -> list storing index of every pair having that sum ; consider every pair ( A [ i ] , A [ j ] ) where ( j > i ) ; calculate sum of current pair ; if sum is already present in the map ; check every pair having desired sum ; if pairs don 't overlap, print  them and return ; Insert current pair into the map ; Driver Code
import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; class Pair { public int x , y ; Pair ( int x , int y ) { this . x = x ; this . y = y ; } } class GFG { public static void findPairs ( int [ ] A ) { Map < Integer , List < Pair > > map = new HashMap < > ( ) ; for ( int i = 0 ; i < A . length - 1 ; i ++ ) { for ( int j = i + 1 ; j < A . length ; j ++ ) { int sum = A [ i ] + A [ j ] ; if ( map . containsKey ( sum ) ) { for ( Pair pair : map . get ( sum ) ) { int x = pair . x ; int y = pair . y ; if ( ( x != i && x != j ) && ( y != i && y != j ) ) { System . out . println ( " Pair ▁ First ( " + A [ i ] + " , ▁ " + A [ j ] + " ) " ) ; System . out . println ( " Pair ▁ Second ▁ ( " + A [ x ] + " , ▁ " + A [ y ] + " ) " ) ; return ; } } } map . putIfAbsent ( sum , new ArrayList < > ( ) ) ; map . get ( sum ) . add ( new Pair ( i , j ) ) ; } } System . out . print ( " No ▁ such ▁ non - overlapping ▁ pairs ▁ present " ) ; } public static void main ( String [ ] args ) { int [ ] A = { 8 , 4 , 7 , 8 , 4 } ; findPairs ( A ) ; } }