Length of the longest subarray whose Bitwise XOR is K | Java program to implement the above approach ; Function to find the length of the longest subarray whose bitwise XOR is equal to K ; Stores prefix XOR of the array ; Stores length of longest subarray having bitwise XOR equal to K ; Stores index of prefix XOR of the array ; Insert 0 into the map ; Traverse the array ; Update prefixXOR ; If ( prefixXOR ^ K ) present in the map ; Update maxLen ; If prefixXOR not present in the Map ; Insert prefixXOR into the map ; Driver Code
import java . util . * ; class GFG { static int LongestLenXORK ( int arr [ ] , int N , int K ) { int prefixXOR = 0 ; int maxLen = 0 ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; mp . put ( 0 , - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { prefixXOR ^= arr [ i ] ; if ( mp . containsKey ( prefixXOR ^ K ) ) { maxLen = Math . max ( maxLen , ( i - mp . get ( prefixXOR ^ K ) ) ) ; } if ( ! mp . containsKey ( prefixXOR ) ) { mp . put ( prefixXOR , i ) ; } } return maxLen ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 7 , 2 } ; int N = arr . length ; int K = 1 ; System . out . print ( LongestLenXORK ( arr , N , K ) ) ; } }