![]() |
VOOZH | about |
Given an array of n integers, find the sum of XOR of all pairs of numbers in the array.
Examples:
Input: arr[] = [7, 3, 5]
Output: 12
Explanation:
All possible pairs and there XOR
Value: (7 ^ 3 = 4) + (3 ^ 5 = 6)
(7 ^ 5 = 2) = 4 + 6 + 2 = 12
Input: arr[] = [5, 9, 7, 6]
Output: 47
Explanation:
All possible pairs and there XOR
Value: (5 ^ 9 = 12) + (5 ^ 7 = 2)
+ (5 ^ 6 = 3) + (9 ^ 7 = 14)
+ (9 ^ 6 = 15) + (7 ^ 6 = 1)
= 12 + 2 + 3 + 14 + 15 + 1 = 47
Table of Content
Iterate over all unique pairs of elements and compute their XOR, adding each result to the total sum.
Dry run for arr[] = [7, 3, 5]:
47
Assume integers are represented using 32 bits. For each bit position, count how many numbers have 0 and how many have 1, then multiply these counts with 2^i (where i is the bit position) to get the contribution of that bit. Summing contributions from all bit positions gives the final answer.
Let us consider rightmost bit as an example.. Suppose a numbers have 0-bit and b numbers have 1-bit at this position. Then, out of all pairs, a * b pairs will have 1 in this bit of the XOR, because there are a * b ways to choose one number with 0 and one with 1. So, this bit contributes a * b to the total XOR sum. In general, for the i-th bit (starting from 0), count numbers with 0 as ai and numbers with 1 as bi so, the contribution is ai * bi * 2^i. Repeat this for all bit positions and sum all contributions to get the final sum.
For arr[] = [7, 3, 5]
47