Open In App

Maximize the number of subarrays with XOR as zero

Given an array of N numbers. The task is to maximize the number of subarrays with XOR value zero by swapping the bits of an array element of any given subarray any number of times. 

Note: 1<=A[i]<=1018

Examples: 

Input: a[] = {6, 7, 14} 
Output :
2 subarrays are {7, 14} and {6, 7 and 14} by swapping their bits individually in subarrays. 
Subarray {7, 14} is valid as 7 is changed to 11(111 to 1011) and 14 is changed to 11, hence the subarray is {11, 11} now. Subarray {6, 7, 14} is valid as 6 is changed to 3 and 7 to 13 and 14 is unchanged, so 3^13^14 = 0.

Input: a[] = {1, 1} 
Output :

Approach: 

The first observation is that only an even number of set bits at any given index can lead to XOR value 0. Since the maximum size of the array elements can be of the order 1018, we can assume 60 bits for swapping. The following steps can be followed to solve the above problem: 

The mathematical work that needs to be done in L-R range for every subarray has been explained above. 

A naive solution will be to iterate for every subarray and check both the conditions explicitly and count the number of such subarrays. But the time complexity in doing so will be O(N^2).

An efficient solution will be to follow the below-mentioned steps: 

Below is the implementation of the above approach: 




#include <bits/stdc++.h>
using namespace std;
 
// Function to count subarrays not satisfying condition 2
int exclude(int a[], int n)
{
    int count = 0;
    // iterate in the array
    for (int i = 0; i < n; i++) {
 
        // store the sum of set bits
        // in the subarray
        int s = 0;
        int maximum = 0;
 
        // iterate for range of 60 subarrays
        for (int j = i; j < min(n, i + 60); j++) {
            s += a[j];
            maximum = max(a[j], maximum);
 
            // check if falsifies the condition-2
            if (s % 2 == 0 && 2 * maximum > s)
                count++;
        }
    }
 
    return count;
}
 
// Function to count subarrays
int countSubarrays(int a[], int n)
{
 
    // replace the array element by number
    // of set bits in them
    for (int i = 0; i < n; i++)
        a[i] = __builtin_popcountll(a[i]);
 
    // calculate prefix array
    int pre[n];
    for (int i = 0; i < n; i++) {
        pre[i] = a[i];
        if (i != 0)
 
            pre[i] += pre[i - 1];
    }
 
    // Count the number of subarrays
    // satisfying step-1
    int odd = 0, even = 0;
 
    // count number of odd and even
    for (int i = 0; i < n; i++) {
        if (pre[i] & 1)
            odd++;
    }
    even = n - odd;
 
    // Increase even by 1 for 1, so that the
    // subarrays starting from the index-0
    // are also taken to count
    even++;
 
    // total subarrays satisfying condition-1 only
    int answer = (odd * (odd - 1) / 2) + (even * (even - 1) / 2);
 
    cout << answer << endl;
 
    // exclude total subarrays not satisfying condition2
    answer = answer - exclude(a, n);
 
    return answer;
}
 
// Driver Code
int main()
{
 
    int a[] = { 6, 7, 14 };
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << countSubarrays(a, n);
 
    return 0;
}




// Java Program to find the minimum element to
// be added such that the array can be partitioned
// into two contiguous subarrays with equal sums
import java.util.*;
 
class GFG
{
 
// Function to count subarrays not satisfying condition 2
static int exclude(int a[], int n)
{
    int count = 0;
    // iterate in the array
    for (int i = 0; i < n; i++)
    {
 
        // store the sum of set bits
        // in the subarray
        int s = 0;
        int maximum = 0;
 
        // iterate for range of 60 subarrays
        for (int j = i; j < Math.min(n, i + 60); j++)
        {
            s += a[j];
            maximum = Math.max(a[j], maximum);
 
            // check if falsifies the condition-2
            if (s % 2 == 0 && 2 * maximum > s)
                count++;
        }
    }
 
    return count;
}
 
// Function to count subarrays
static int countSubarrays(int a[], int n)
{
 
    // replace the array element by number
    // of set bits in them
    for (int i = 0; i < n; i++)
        a[i] = Integer.bitCount(a[i]);
 
    // calculate prefix array
    int []pre = new int[n];
    for (int i = 0; i < n; i++)
    {
        pre[i] = a[i];
        if (i != 0)
 
            pre[i] += pre[i - 1];
    }
 
    // Count the number of subarrays
    // satisfying step-1
    int odd = 0, even = 0;
 
    // count number of odd and even
    for (int i = 0; i < n; i++)
    {
        if (pre[i]%2== 1)
            odd++;
    }
    even = n - odd;
 
    // Increase even by 1 for 1, so that the
    // subarrays starting from the index-0
    // are also taken to count
    even++;
 
    // total subarrays satisfying condition-1 only
    int answer = (odd * (odd - 1) / 2) + (even * (even - 1) / 2);
 
    System.out.println(answer);
 
    // exclude total subarrays not satisfying condition2
    answer = answer - exclude(a, n);
 
    return answer;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = { 6, 7, 14 };
    int n = a.length;
 
    System.out.println(countSubarrays(a, n));
}
}
 
// This code is contributed by Rajput-Ji




# Python3 code for the given approach.
 
# Function to count subarrays not
# satisfying condition 2
def exclude(a, n):
 
    count = 0
     
    # iterate in the array
    for i in range(0, n):
 
        # store the sum of set bits
        # in the subarray
        s = 0
        maximum = 0
 
        # iterate for range of 60 subarrays
        for j in range(i, min(n, i + 60)):
            s += a[j]
            maximum = max(a[j], maximum)
 
            # check if falsifies the condition-2
            if s % 2 == 0 and 2 * maximum > s:
                count += 1
 
    return count
 
# Function to count subarrays
def countSubarrays(a, n):
 
    # replace the array element by
    # number of set bits in them
    for i in range(0, n):
        a[i] = bin(a[i]).count('1')
 
    # calculate prefix array
    pre = [None] * n
    for i in range(0, n):
        pre[i] = a[i]
         
        if i != 0:
            pre[i] += pre[i - 1]
     
    # Count the number of subarrays
    # satisfying step-1
    odd, even = 0, 0
 
    # count number of odd and even
    for i in range(0, n):
        if pre[i] & 1:
            odd += 1
     
    even = n - odd
 
    # Increase even by 1 for 1, so that the
    # subarrays starting from the index-0
    # are also taken to count
    even += 1
 
    # total subarrays satisfying condition-1 only
    answer = ((odd * (odd - 1) // 2) +
             (even * (even - 1) // 2))
 
    print(answer)
 
    # exclude total subarrays not
    # satisfying condition2
    answer = answer - exclude(a, n)
 
    return answer
 
# Driver Code
if __name__ == "__main__":
 
    a = [6, 7, 14]
    n = len(a)
 
    print(countSubarrays(a, n))
     
# This code is contributed by Rituraj Jain




// C# Program to find the minimum element to
// be added such that the array can be partitioned
// into two contiguous subarrays with equal sums
using System;
     
class GFG
{
 
// Function to count subarrays not satisfying condition 2
static int exclude(int []a, int n)
{
    int count = 0;
    // iterate in the array
    for (int i = 0; i < n; i++)
    {
 
        // store the sum of set bits
        // in the subarray
        int s = 0;
        int maximum = 0;
 
        // iterate for range of 60 subarrays
        for (int j = i; j < Math.Min(n, i + 60); j++)
        {
            s += a[j];
            maximum = Math.Max(a[j], maximum);
 
            // check if falsifies the condition-2
            if (s % 2 == 0 && 2 * maximum > s)
                count++;
        }
    }
 
    return count;
}
 
// Function to count subarrays
static int countSubarrays(int []a, int n)
{
 
    // replace the array element by number
    // of set bits in them
    for (int i = 0; i < n; i++)
        a[i] = bitCount(a[i]);
 
    // calculate prefix array
    int []pre = new int[n];
    for (int i = 0; i < n; i++)
    {
        pre[i] = a[i];
        if (i != 0)
 
            pre[i] += pre[i - 1];
    }
 
    // Count the number of subarrays
    // satisfying step-1
    int odd = 0, even = 0;
 
    // count number of odd and even
    for (int i = 0; i < n; i++)
    {
        if (pre[i]%2== 1)
            odd++;
    }
    even = n - odd;
 
    // Increase even by 1 for 1, so that the
    // subarrays starting from the index-0
    // are also taken to count
    even++;
 
    // total subarrays satisfying condition-1 only
    int answer = (odd * (odd - 1) / 2) + (even * (even - 1) / 2);
 
    Console.WriteLine(answer);
 
    // exclude total subarrays not satisfying condition2
    answer = answer - exclude(a, n);
 
    return answer;
}
 
static int bitCount(long x)
{
    int setBits = 0;
    while (x != 0) {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = { 6, 7, 14 };
    int n = a.Length;
 
    Console.WriteLine(countSubarrays(a, n));
}
}
 
// This code is contributed by Rajput-Ji




<script>
 
// Function to count subarrays not
// satisfying condition 2
function exclude(a, n)
{
    let count = 0;
    // iterate in the array
    for (let i = 0; i < n; i++)
    {
 
        // store the sum of set bits
        // in the subarray
        let s = 0;
        let maximum = 0;
 
        // iterate for range of 60 subarrays
        for (let j = i; j < Math.min(n, i + 60); j++)
        {
            s += a[j];
            maximum = Math.max(a[j], maximum);
 
            // check if falsifies the condition-2
            if (s % 2 == 0 && 2 * maximum > s)
                count++;
        }
    }
 
    return count;
}
 
// Function to count subarrays
function countSubarrays(a, n)
{
 
    // replace the array element by number
    // of set bits in them
    for (let i = 0; i < n; i++)
        a[i] = bitCount(a[i]);
 
    // calculate prefix array
    let pre = new Array(n);
    for (let i = 0; i < n; i++) {
        pre[i] = a[i];
        if (i != 0)
 
            pre[i] += pre[i - 1];
    }
 
    // Count the number of subarrays
    // satisfying step-1
    let odd = 0, even = 0;
 
    // count number of odd and even
    for (let i = 0; i < n; i++) {
        if (pre[i] & 1)
            odd++;
    }
    even = n - odd;
 
    // Increase even by 1 for 1, so that the
    // subarrays starting from the index-0
    // are also taken to count
    even++;
 
    // total subarrays satisfying condition-1 only
    let answer = parseInt((odd * (odd - 1) / 2) +
                 (even * (even - 1) / 2));
 
    document.write(answer + "<br>");
 
    // exclude total subarrays not
    // satisfying condition2
    answer = answer - exclude(a, n);
 
    return answer;
}
 
function bitCount(x)
{
    let setBits = 0;
    while (x != 0) {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
 
// Driver Code
 
    let a = [ 6, 7, 14 ];
    let n = a.length;
 
    document.write(countSubarrays(a, n));
 
</script>

Output
3
2

Complexity Analysis:


Article Tags :