Make Array elements equal by replacing adjacent elements with their XOR | C ++ Program of the above approach ; Function to check if it is possible to make all the array elements equal using the given operation ; Stores the prefix XOR array ; Calculate prefix [ i ] ; Case 1 , check if the XOR of the input array is 0 ; Case 2 Iterate over all the ways to divide the array into three non empty subarrays ; XOR of Middle Block ; XOR of Left Block ; XOR of Right Block ; Not Possible ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleEqualArray ( int A [ ] , int N ) { vector < int > pref ( N ) ; pref [ 0 ] = A [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { pref [ i ] = pref [ i - 1 ] ^ A [ i ] ; } if ( pref [ N - 1 ] == 0 ) { cout << " YES " ; return ; } int cur_xor = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { cur_xor ^= A [ i ] ; for ( int j = 0 ; j < i ; j ++ ) { if ( j ) { int middle_xor = pref [ j - 1 ] ^ pref [ i - 1 ] ; int left_xor = pref [ j - 1 ] ; int right_xor = cur_xor ; if ( left_xor == middle_xor && middle_xor == right_xor ) { cout << " YES " ; return ; } } } } cout << " NO " ; } int main ( ) { int A [ ] = { 0 , 2 , 2 } ; int N = sizeof ( A ) / sizeof ( int ) ; possibleEqualArray ( A , N ) ; return 0 ; }