VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-number-pairs-array-xor-0/

⇱ Find number of pairs in an array such that their XOR is 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find number of pairs in an array such that their XOR is 0

Last Updated : 1 Aug, 2022

Given an array of size N. Find the number of pairs (i, j) such that XOR = 0, and 1 <= i < j <= N.

Examples : 

Input : A[] = {1, 3, 4, 1, 4}
Output : 2
Explanation : Index (0, 3) and (2, 4)

Input : A[] = {2, 2, 2}
Output : 3
Recommended Practice

First Approach : Sorting
XOR = 0 is only satisfied when . Therefore, we will first sort the array and then count the frequency of each element. By combinatorics, we can observe that if frequency of some element is then, it will contribute to the answer. 
Below is the implementation of above approach:


Output
2

Time Complexity : O(N Log N) 
Auxiliary Space: O(1), as no extra space is used

Second Approach: Hashing (Index Mapping)

Solution is handy, if we can count the frequency of each element in the array. Index mapping technique can be used to count the frequency of each element.

Below is the implementation of above approach : 


Output
2

Time Complexity: O(N)
Auxiliary Space: O(N)

Note : Index Mapping method can only be used when the numbers in the array are not large. In such cases, sorting method can be used. 

Comment
Article Tags:
Article Tags: