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 ) ) { List < int > al = m ; al . Add ( arr [ i ] ) ; m = al ; } else { List < int > al = new List < int > ( ) ; al . Add ( arr [ i ] ) ; m . Add ( diff , al ) ; } }