- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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.

## Example

#include<iostream> #include<algorithm> 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]){ count++; } } if(arr[0] == arr[n-1]) count++; 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); }

## Output

Number of pairs: 2

- Related Articles
- Count ordered pairs of positive numbers such that their sum is S and XOR is K in C++
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- Find the Number of Prime Pairs in an Array using C++
- Find the Number of Unique Pairs in an Array using C++
- Sum of XOR of all pairs in an array in C++
- Find all pairs (a, b) in an array such that a % b = k in C++
- Count of pairs (x, y) in an array such that x < y in C++
- Sum of XOR of sum of all pairs in an array in C++
- Count pairs in an array such that at least one element is prime in C++
- Count all pairs of adjacent nodes whose XOR is an odd number in C++
- Count pairs in an array such that frequency of one is at least value of other in C++
- Find XOR of two number without using XOR operator in C++
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Find prime number K in an array such that (A[i] % K) is maximum in C++
- Find the Number Whose Sum of XOR with Given Array Range is Maximum using C++

Advertisements