 GeeksforGeeks App
Open App Browser
Continue

# 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:

• Since only the number of set bits is required, count the number of set bits in every i-th element.
• There are two conditions that need to be satisfied simultaneously in order to make the XOR of any subarray zero by swapping bits. The conditions are as follows:
1. If there are even a number of set bits in any range L-R, then we can try making the XOR of subarray 0.
2. If the sum of the bits is less than or equal to twice of the largest number of set bits in any given range, then it is possible to make its XOR zero.

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:

• Use prefix[] sum array to compute the number of subarrays that obey the first condition only.
• Step-1 gives us the number of subarrays which is a sum of bits as even in O(N) complexity.
• Using inclusion-exclusion principle, we can explicitly subtract the number of subarrays whose 2*largest number of set bits in subarray exceeds the sum of set bits in the subarray.
• Using maths, we can reduce the number of subarray checking in Step-3, since the number of set bits can be a minimum of 1, we can just check for every subarray of length 60, since beyond that length, the second condition can never be falsified.
• Once done we can subtract the number from the number of subarrays obtained in Step-1 to get our answer.

Below is the implementation of the above approach:

## C++

 `#include ``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);` `    ``cout << countSubarrays(a, n);` `    ``return` `0;``}`

## Java

 `// 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

 `# 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#

 `// 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`

## Javascript

 ``

Output

```3
2```

Complexity Analysis:

• Time Complexity: O(N*60), as we are using a loop to traverse N*60 times.
• Auxiliary Space: O(N), as we are using extra space for pre array.

My Personal Notes arrow_drop_up