Find number of pairs in an array such that their XOR is 0 using C++.

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements; we have to find a number of pairs in the array whose XOR will be 0. The pair (x, y) whose XOR is 0, then x = y. To solve it we can sort the array, then if two consecutive elements are the same, increase the count. If all elements are the same, then the last count may not be counted. In that case, we will check whether the last and first elements are the same or not, if the same, then increase the count by 1.


using namespace std;
int countPairs(int arr[], int n) {
   int count = 0;
   sort(arr, arr+n);
   for(int i = 0; i<n - 1; i++){
      if(arr[i] == arr[i+1]){
   if(arr[0] == arr[n-1])
   return count;
int main() {
   int arr[] = {1, 2, 1, 2, 4};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Number of pairs: " << countPairs(arr, n);


Number of pairs: 2
Published on 30-Oct-2019 10:39:40