Check whether an Array can be made 0 by splitting and merging repeatedly

 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).


You have to determine whether it is possible to convert array A to size 1, containing a single element equal to 0 after several splits and/or merges?


Input: arr = [9, 17]

Output: Yes

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 = [1]

Output: No


public class codefile{
    static boolean check(int[]  input){
         int i, ctr = 0;
         
    for(i = 0; i < input.length; i++)
    {
     
       // Check if element is odd
       if (input[i] % 2 == 1)
       {
           ctr++;
       }
    }
     
    // According to the logic
    // in above approach
    if (ctr % 2 == 1)
    {
        return false;
    }
    else
    {
        return true;
    }
    }
}

Approach 2:-

public class codefile{
    static boolean check(int[]  input){
       
        int n = input.length;
        // variable to store the value of XOR
        int xor = 0;
        // traversing the array
        for (int i = 0; i < n; i++) {
            xor ^= input[i];
        }
        // checking if the value of XOR is even or odd
        // if even printing YES else ONO
        if (xor % 2 == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence