Maximize the number of subarrays with XOR as zero
Last Updated :
06 Sep, 2022
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
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:
- If there are even a number of set bits in any range L-R, then we can try making the XOR of subarray 0.
- 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 <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
// 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
<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>
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read