VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-xor-pairs-array/

⇱ Sum of XOR of all pairs in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of XOR of all pairs in an array

Last Updated : 9 Apr, 2026

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

[Naive Approach] Iterative Method - O(n^2) Time and O(1) Space

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]:

  • Initial sum = 0
  • i = 0 (7)
    j = 1: 7 ^ 3 = 4 then add to sum, now sum = 4
    j = 2: 7 ^ 5 = 2 then add to sum, now sum = 6
  • i = 1 (3)
    j = 2: 3 ^ 5 = 6 then add to sum, now sum = 12
  • All unique pairs are processed, Final sum = 12

Output
47

[Expected Approach] Bit Manipulation - O(n) Time and O(1) Space

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.

How this actually works?

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]

  1. Binary representation:
    7 = 1 1 1
    3 = 0 1 1
    5 = 1 0 1
  2. For bit position 0 (rightmost bit):
    Bits with zero = 0
    Bits with one = 3
    Contribution = 0 * 3 * 2^0 = 0
  3. For bit position 1:
    Bits with zero = 1
    Bits with one = 2
    Contribution = 1 * 2 * 2^1 = 4
  4. For bit position 2:
    Bits with zero = 1
    Bits with one = 2
    Contribution = 1 * 2 * 2^2 = 8
  5. Final sum = 0 + 4 + 8 = 12

Output
47



Comment
Article Tags: