Sum of XOR of all sub | C ++ implementation of above approach ; Sum of XOR of all K length sub - array of an array ; If the length of the array is less than k ; Array that will store xor values of subarray from 1 to i ; Traverse through the array ; If i is greater than zero , store xor of all the elements from 0 to i ; If it is the first element ; If i is greater than k ; Xor of values from 0 to i ; Now to find subarray of length k that ends at i , xor sum with x [ i - k ] ; Add the xor of elements from i - k + 1 to i ; Return the resultant sum ; ; Driver code
#include <iostream> NEW_LINE using namespace std ; int FindXorSum ( int arr [ ] , int k , int n ) { if ( n < k ) return 0 ; int x [ n ] = { 0 } ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i > 0 ) x [ i ] = x [ i - 1 ] ^ arr [ i ] ; else x [ i ] = arr [ i ] ; if ( i >= k - 1 ) { int sum = 0 ; sum = x [ i ] ; if ( i - k > -1 ) sum ^= x [ i - k ] ; result += sum ; } } return result ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = 4 , k = 2 ; cout << FindXorSum ( arr , k , n ) << endl ; return 0 ; }