Can someone explain the optimal solution for finding the sum of XOR of all sub-arrays of the array. Example:

Input : arr[] = {3, 8, 13} Output : 46

XOR of {3} = 3 XOR of {3, 8} = 11 XOR of {3, 8, 13} = 6 XOR of {8} = 8 XOR of {8, 13} = 5 XOR of {13} = 13

Sum = 3 + 11 + 6 + 8 + 5 + 13 = 46

Thanks in Advance.

It's a pretty standard problem you may get it here

I didn't understand the O(N) solution can you please explain.

Yeah, sure! Let's assume the array as bits and you want to find the no of subarrays having a particular bit (say

ithbit) set.so let's assume the above example {3, 8, 13} as,

so, now find no of subarrays with odd 1s for each of the bits.

so how can we do this? see we can count no of subarrays starting with 0th index and have odd 1s then we can iterate over all $$$i$$$ letting it to be the starting index of the subarrays.

so let say, for ith index have $$$x$$$ subarrays with odd 1s.

if we encounter 1 at $$$ith$$$ index then for upcoming subarrays the behavior would become opposite (i.e. even 1s subarrays would act like odd 1s subarrays) wo we would do $$${x = n - i - x}$$$ where $$${n - i}$$$ is the number of subarrays starting with $$$ith$$$ index.

So, we will sum-up all the no of subarrays with odd 1s for each bit (say $$$sum_i$$$).

so our answer would be $$${\sum sum_i * 2 ^ i}$$$. here $$$2^i$$$ is the contribution of $$$ith$$$ bit.

I have a variation of this problem whose statement is as follows :

You are given an array of int values, of length N. For a subarray it's score is defined as xor of all elements present in the subarray. Your goal is to choose any two non-overlapping subarrays such that sum of their scores is maximum possible. Print the maximum sum.How will You solve this problem ?

Note: By non overlapping i mean : 0<=i1<=j1<i2<=j2<NI think we can easily do this problem using $$$Trie$$$ data structure as let say I am iterating on i [0...n-1] and storing all the $$$prefixs$$$ in the trie and at $$$ith$$$ index I would try to find the $$$maximumXor$$$ with current $$$prefix_i$$$ in the trie as

which would give me $$$Xor$$$ of subarray [j...i]

which would be the maximum xor subarray possible in [0...i]. and then I may store it in an array (say, $$$prefixMax$$$).

where $$${prefixMax_i = max(maximumXor, prefixMax_{i - 1})}$$$ Similarly I may do this with suffix one as well after clearing the trie. so now we can find our answer as maximum over all $$${prefixMax_i + suffixMax_{i + 1}}$$$.

UPD :My CodeBtw can you share the problem link?

I'm so dumb, I still can't get it.

Me as well . it needs some prerequisites in dp , specifically number of subarrays with odd sum here's a leetcode problem