Count pairs whose XOR has an odd number of set bits

Updated

Given an array A of size N, the task is to count the number of pairs such that their XOR value has odd number of set bits in it.

Examples :

Input : arr[] = {1, 2, 3, 4, 5}, N = 5
Output : 6
Explanation :
The possible pairs are {1, 3}, {1, 5}, {2, 3}, {2, 5}, {3, 4}, {4, 5}

Input : arr[] = {1, 4, 9, 16, 25}, N=5
Output : 4

Approach :

The idea is to generate all possible pairs of the given array and check whether the XOR of the pair has an odd number of set bits. If it has odd number of set bits, count it, otherwise ignore it.

Implementation :

// Java Program for
// the above approach
class Main {

    // Function to count the
    // number of pairs with their
    // XOR having odd number
    // of set bits
    static void countPairs(int a[], int n)
    {
        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                int val = a[i] ^ a[j];
                if (Integer.bitCount(val) % 2 != 0) {
                    count++;
                }
            }
        }
        System.out.println(count);
    }

    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5 };
        int N = arr.length;
        countPairs(arr, N);
    }
}
Output

6

Time Complexity : O(N2)

Auxillary Space: O(1)

Comment
Mithlesh Upadhyay Published 30 Nov 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials