Count all pairs with given XOR
Given an array of distinct positive integers and a number x, find the number of pairs of integers in the array whose XOR is equal to x.
Examples:
Input : arr[] = {5, 4, 10, 15, 7, 6}, x = 5
Output : 1
Explanation : (10 ^ 15) = 5
Input : arr[] = {3, 6, 8, 10, 15, 50}, x = 5
Output : 2
Explanation : (3 ^ 6) = 5 and (10 ^ 15) = 5
A Simple solution is to traverse each element and check if there’s another number whose XOR with it is equal to x. This solution takes O(n2) time. An efficient solution to this problem takes O(n) time. The idea is based on the fact that arr[i] ^ arr[j] is equal to x if and only if arr[i] ^ x is equal to arr[j].
1) Initialize result as 0.
2) Create an empty hash set "s".
3) Do following for each element arr[i] in arr[]
(a) If x ^ arr[i] is in "s", then increment result by 1.
(b) Insert arr[i] into the hash set "s".
3) return result.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int xorPairCount( int arr[], int n, int x)
{
int result = 0;
unordered_set< int > s;
for ( int i=0; i<n ; i++)
{
if (s.find(x^arr[i]) != s.end())
result++;
s.insert(arr[i]);
}
return result;
}
int main()
{
int arr[] = {5 , 4 ,10, 15, 7, 6};
int n = sizeof (arr)/ sizeof (arr[0]);
int x = 5;
cout << "Count of pairs with given XOR = "
<< xorPairCount(arr, n, x);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int xorPairCount( int arr[], int n, int x)
{
int result = 0 ;
HashSet<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
{
if (s.contains(x ^ arr[i]) &&
(x ^ arr[i]) == ( int ) s.toArray()[s.size() - 1 ])
{
result++;
}
s.add(arr[i]);
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 5 , 4 , 10 , 15 , 7 , 6 };
int n = arr.length;
int x = 5 ;
System.out.print( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
|
Python3
def xorPairCount(arr, n, x):
result = 0
s = set ()
for i in range ( 0 , n):
if (x ^ arr[i] in s):
result = result + 1
s.add(arr[i])
return result
if __name__ = = "__main__" :
arr = [ 5 , 4 , 10 , 15 , 7 , 6 ]
n = len (arr)
x = 5
print ( "Count of pair with given XOR = " +
str (xorPairCount(arr, n, x)))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int xorPairCount( int []arr, int n, int x)
{
int result = 0;
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
if (s.Contains(x ^ arr[i]))
{
result++;
}
s.Add(arr[i]);
}
return result;
}
public static void Main()
{
int []arr = {5, 4, 10, 15, 7, 6};
int n = arr.Length;
int x = 5;
Console.WriteLine( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
|
Javascript
<script>
function xorPairCount(arr,n,x)
{
let result = 0;
let s = new Set();
for (let i = 0; i < n; i++)
{
if (s.has(x ^ arr[i]) )
{
result++;
}
s.add(arr[i]);
}
return result;
}
let arr=[5, 4, 10, 15, 7, 6];
let n = arr.length;
let x = 5;
document.write( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
</script>
|
Output
Count of pairs with given XOR = 1
Time complexity : O(n)
Auxiliary Space: O(n)
How to handle duplicates?
The above efficient solution doesn’t work if there are duplicates in the input array. For example, the above solution produces different results for {2, 2, 5} and {5, 2, 2}. To handle duplicates, we store counts of occurrences of all elements. We use unordered_map instead of unordered_set.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int xorPairCount( int arr[], int n, int x)
{
int result = 0;
unordered_map< int , int > m;
for ( int i=0; i<n ; i++)
{
int curr_xor = x^arr[i];
if (m.find(curr_xor) != m.end())
result += m[curr_xor];
m[arr[i]]++;
}
return result;
}
int main()
{
int arr[] = {2, 5, 2};
int n = sizeof (arr)/ sizeof (arr[0]);
int x = 0;
cout << "Count of pairs with given XOR = "
<< xorPairCount(arr, n, x);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int xorPairCount( int arr[], int n, int x)
{
int result = 0 ;
Map<Integer,Integer> m = new HashMap<>();
for ( int i = 0 ; i < n ; i++)
{
int curr_xor = x^arr[i];
if (m.containsKey(curr_xor))
result += m.get(curr_xor);
if (m.containsKey(arr[i]))
{
m.put(arr[i], m.get(arr[i]) + 1 );
}
else {
m.put(arr[i], 1 );
}
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 2 , 5 , 2 };
int n = arr.length;
int x = 0 ;
System.out.println( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
|
Python3
def xorPairCount(arr, n, x):
result = 0
m = dict ()
for i in range (n):
curr_xor = x ^ arr[i]
if (curr_xor in m.keys()):
result + = m[curr_xor]
if arr[i] in m.keys():
m[arr[i]] + = 1
else :
m[arr[i]] = 1
return result
arr = [ 2 , 5 , 2 ]
n = len (arr)
x = 0
print ( "Count of pairs with given XOR = " ,
xorPairCount(arr, n, x))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int xorPairCount( int []arr, int n, int x)
{
int result = 0;
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n ; i++)
{
int curr_xor = x^arr[i];
if (m.ContainsKey(curr_xor))
result += m[curr_xor];
if (m.ContainsKey(arr[i]))
{
var val = m[arr[i]];
m.Remove(arr[i]);
m.Add(arr[i], val + 1);
}
else
{
m.Add(arr[i], 1);
}
}
return result;
}
public static void Main(String[] args)
{
int []arr = {2, 5, 2};
int n = arr.Length;
int x = 0;
Console.WriteLine( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
}
}
|
Javascript
<script>
function xorPairCount(arr, n, x)
{
let result = 0;
let m = new Map();
for (let i = 0; i < n ; i++)
{
let curr_xor = x^arr[i];
if (m.has(curr_xor))
result += m.get(curr_xor);
if (m.has(arr[i]))
{
m.set(arr[i], m.get(arr[i]) + 1);
}
else {
m.set(arr[i], 1);
}
}
return result;
}
let arr = [2, 5, 2];
let n = arr.length;
let x = 0;
document.write( "Count of pairs with given XOR = "
+ xorPairCount(arr, n, x));
</script>
|
Output
Count of pairs with given XOR = 1
Time complexity : O(n)
Auxiliary Space: O(n)
Last Updated :
06 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...