Check whether an Array can be made 0 by splitting and merging repeatedly
Given an array arr with N elements, the task is to find whether all the elements of the given array can be made 0 by given operations. Only 2 types of operations can be performed on this array:
- Split an element B into 2 elements C and D such that B = C + D.
- Merge 2 elements P and Q as one element R such that R = P^Q i.e. (XOR of P and Q).
Input: arr = [9, 17]
Explanation: Following is one possible sequence of operations –
1) Merge i.e 9 XOR 17 = 24
2) Split 24 into two parts each of size 12
3) Merge i.e 12 XOR 12 = 0
As there is only 1 element i.e 0. So it is possible.
Input: arr = 
Explanation: There is no possible way to make it 0.
- If any element in the array is even then it can be made 0. Split that element in two equal parts of arr[i]/2 and arr[i]/2. XOR of two equal numbers is zero. Therefore this strategy makes an element 0.
- If any element is odd. Split it into two parts: 1 and arr[i]-1. Since arr[i]-1 is even, it can be made 0 by the above strategy. Therefore an odd element can reduce its size to 1. Two odd elements can, therefore, be made 0 by following above strategy and finally XOR them (i.e. 1) as 1 XOR 1 = 0. Therefore if the number of odd elements in the array is even, then the answer is possible. Otherwise, an element of value 1 will be left and it is not possible to satisfy the condition.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.