Length of the longest subarray whose Bitwise XOR is K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestLenXORK ( int arr [ ] , int N , int K ) { int prefixXOR = 0 ; int maxLen = 0 ; map < int , int > mp ; mp [ 0 ] = -1 ; for ( int i = 0 ; i < N ; i ++ ) { prefixXOR ^= arr [ i ] ; if ( mp . count ( prefixXOR ^ K ) ) { maxLen = max ( maxLen , ( i - mp [ prefixXOR ^ K ] ) ) ; } if ( ! mp . count ( prefixXOR ) ) { mp [ prefixXOR ] = i ; } } return maxLen ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; cout << LongestLenXORK ( arr , N , K ) ; return 0 ; }