Adjacency list to store neighbors of each array element
for ( Pair it : A ) { List < Integer > temp ; temp = ( mp . containsKey ( it . first ) ) ? mp . get ( it . first ) : new ArrayList < Integer > ( ) ; temp . add ( it . second ) ; mp . put ( it . first , temp ) ; temp = ( mp . containsKey ( it . second ) ) ? mp . get ( it . second ) : new ArrayList < Integer > ( ) ; temp . add ( it . first ) ; mp . put ( it . second , temp ) ; } int it = 0 ;