Open In App

Count ways to split array into three non-empty subarrays having equal Bitwise XOR values

Last Updated : 29 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Share
1 Like
Like
Report

Given an array arr[] consisting of N non-negative integers, the task is to count the number of ways to split the array into three different non-empty subarrays such that Bitwise XOR of each subarray is equal. 

Examples:

Input: arr[] = {7, 0, 5, 2, 7} 
Output: 2
Explanation: All possible ways are:
{{7}, {0, 5, 2}, {7}} where XOR value of each subarray is 7
{{7, 0}, {5, 2}, {7}} where XOR value of each subarray is 7

Input: arr[] = {3, 1, 4}
Output: 0

 

Naive Approach: The simplest approach is to split the array into three non-empty subarrays using three loops and check whether the XOR of each subarray are equal or not. If the given condition holds true, then increase the final count. Print the final count obtained. 

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the following observations:

  • Let xor_arr be the XOR of all elements of the array arr[].
  • If arr[] can be split into three different subarrays of equal XOR values, then XOR of all elements in each subarray will be equal to xor_arr.
  • So, the idea is to find all the prefix and suffix arrays with XOR value equal to xor_arr.
  • If the total length of such a prefix and suffix array is less than N, then there exists another subarray between them with XOR value equal to xor_arr.

Hence, count the total number of all such prefix and suffix arrays that satisfy the above condition. Follow the steps below to solve the given problem:

  • Store the XOR of all elements of the array, arr[] in a variable xor_arr.
  • Create an array, pref_ind[] to store the ending points of every prefix array whose XOR value is equal to xor_arr.
  • Traverse the array, arr[] and insert the ending points of every prefix array whose XOR value is equal to xor_arr in pref_ind.
  • Create another array, suff_inds[] of size N where suff_inds[i] stores the total number of suffix arrays with XOR value equal to xor_arr whose starting point is greater than or equal to i.
  • Traverse the array, arr[] in reverse order to fill the suff_inds[] array. If the current suffix array XOR value equals xor_arr, then increment suff_inds[i] by 1. Also, add the value of suff_inds[i+1] to suff_inds[i].
  • For every element idx in pref_ind if the value of idx < N-1, then add the value of suff_inds[idx + 2] to the final count.
  • Finally, print the value of the final count as the result.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output: 
2

 

Time Complexity: O(N)
Auxiliary Space: O(N)


 


Next Article

Similar Reads