Store values in a map with the difference with X as key
for ( int i = 0 ; i < n ; i ++ ) { int diff = Math . abs ( x - arr [ i ] ) ; if ( m . containsKey ( diff ) ) { ArrayList < Integer > al = m . get ( diff ) ; al . add ( arr [ i ] ) ; m . put ( diff , al ) ; } else { ArrayList < Integer > al = new ArrayList < > ( ) ; al . add ( arr [ i ] ) ; m . put ( diff , al ) ; } }