Find sum of xor of all unordered triplets of the array
Given an array A, consisting of N non-negative integers, find the sum of xor of all unordered triplets of the array. For unordered triplets, the triplet (A[i], A[j], A[k]) is considered the same as triplets (A[j], A[i], A[k]) and all the other permutations.
Since the answer can be large, calculate its mod to 10037.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : A = [3, 5, 2, 18, 7] Output : 132 Input : A = [140, 1, 66] Output : 207
Iterate over all the unordered triplets and add xor of each to the sum.
- An important point to observe is that xor is independent of all the bits. So we can do the required computation over each bit individually.
- Let’s consider the k’th bit of all the array elements. If the number of unordered triplets is k’th bit xor 1 be C, we can simply add C * 2k to the answer. Let the number of elements whose k’th bit is 1 be X and whose k’th bit is 0 be Y. Then find the unordered triplets whose k’th bits xor to 1 can be formed using two cases:
- Only one of the three elements has k’th bit 1.
- All three of them have k’th bit 1.
- Number of ways to select 3 elements having k’th bit 1 =
- Number of ways to select 1 element with k’th bit 1 and rest with 0 =
- We will use nCr mod p to compute the combinatorial function values.
Below is the implementation of the above approach.
Time Complexity : O(32 * N)