Maximum XOR of Two Numbers in an Array | Java implementation of the above approach ; Function to return the maximum xor ; set the i 'th bit in mask  like 100000, 110000, 111000.. ; Just keep the prefix till i ' th ▁ bit ▁ neglecting ▁ all ▁ ▁ the ▁ bit ' s after i 'th bit ; find two pair in set such that a ^ b = newMaxx which is the highest possible bit can be obtained ; clear the set for next iteration ; Driver Code
import java . util . * ; class GFG { static int max_xor ( int arr [ ] , int n ) { int maxx = 0 , mask = 0 ; HashSet < Integer > se = new HashSet < Integer > ( ) ; for ( int i = 30 ; i >= 0 ; i -- ) { mask |= ( 1 << i ) ; for ( int j = 0 ; j < n ; ++ j ) { se . add ( arr [ j ] & mask ) ; } int newMaxx = maxx | ( 1 << i ) ; for ( int prefix : se ) { if ( se . contains ( newMaxx ^ prefix ) ) { maxx = newMaxx ; break ; } } se . clear ( ) ; } return maxx ; } public static void main ( String [ ] args ) { int arr [ ] = { 25 , 10 , 2 , 8 , 5 , 3 } ; int n = arr . length ; System . out . println ( max_xor ( arr , n ) ) ; } }