Pairs with given XOR

 Given an array A[]  of size N of distinct positive integers and a number X, find the number of pairs of integers in the array whose XOR is equal to X.


Example 1:

Input: 
N = 6
A[] = {5, 4, 10, 15, 7, 6}
X = 5
Output: 1
Explanation: (10 ^ 15) = 5


Example 2:

Input: 
N = 6
A[] = {3, 6, 8, 10, 15, 50}
X = 5
Output: 2
Explanation: (3 ^ 6) = 5 and (10 ^ 15) = 5 






c++ implementation:

int countPair(int n, int a[], int x)
    {
        unordered_map<int,int>m;
        int c=0;
        for(int i=0;i<n;i++)
        {
            if(m.find(x^a[i])!=m.end())
            c=c+m[x^a[i]];
            
            m[a[i]]++;
        }
     return c;
    }
Time Complexity: O(n) 

space Complexity: O(n) 




 

No comments

darkmode