### HEIR_OF_SLYTHERIN's blog

By HEIR_OF_SLYTHERIN, history, 16 months ago, 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 Comments (8)
•  » » » Yeah, sure! Let's assume the array as bits and you want to find the no of subarrays having a particular bit (say ith bit) set.so let's assume the above example {3, 8, 13} as, for 0th bit, {1, 0, 1} for 1th bit, {1, 0, 0} for 2nd bit, {0, 0, 1} for 3rd bit, {0, 1, 1} 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.
•  » » » » » 16 months ago, # ^ | ← Rev. 3 →   I 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 ${maximumXor = prefix_i}$ ^ ${prefix_j, (0 \le j < i)}$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 Code