Count of subarrays of size K with elements having even frequencies | C ++ program to count subarrays of size K with all elements having even frequencies ; Function to return count of required subarrays ; If K is odd ; Not possible to have any such subarrays ; Stores the starting index of every subarrays ; Stores the count of required subarrays ; Stores Xor of the current subarray . ; Xor of first subarray of size K ; If all elements appear even number of times , increase the count of such subarrays ; Remove the starting element from the current subarray ; Traverse the array for the remaining subarrays ; Update Xor by adding the last element of the current subarray ; Increment i ; If currXor becomes 0 , then increment count ; Update currXor by removing the starting element of the current subarray ; Return count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubarray ( int arr [ ] , int K , int N ) { if ( K % 2 != 0 ) return 0 ; if ( N < K ) return 0 ; int start = 0 ; int i = 0 ; int count = 0 ; int currXor = arr [ i ++ ] ; while ( i < K ) { currXor ^= arr [ i ] ; i ++ ; } if ( currXor == 0 ) count ++ ; currXor ^= arr [ start ++ ] ; while ( i < N ) { currXor ^= arr [ i ] ; i ++ ; if ( currXor == 0 ) count ++ ; currXor ^= arr [ start ++ ] ; } return count ; } int main ( ) { int arr [ ] = { 2 , 4 , 4 , 2 , 2 , 4 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countSubarray ( arr , K , N ) ) ; }