Last Updated: 31 Jan, 2018

XOR Pairs

Easy
Asked in company
HashedIn

Problem statement

You are given an array ‘A’ of size ‘N’. Return true if an array can be divided into groups of pairs such that XOR of each pair is equal to 0.

A pair consists of two integers.

Example : Let the array be { 1, 2, 3, 4}

One of the ways to divide it into groups of pairs is { 1, 2 } and { 3, 4}.

Input format :
The first line contains a single integer ‘T’ representing the number of test cases.Then test cases follows :

The first line of each test case contains an integer ‘N’.

The second line of each test case contains ‘N’ space-separated integers denoting the elements of array ‘A’.
Output Format :
For each test case, print true if the array can be divided into groups of pairs with XOR 0, else print false.

Print the output of each test case in a new line.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^5

Time Limit : 1 sec

Approaches

01 Approach

Approach : 

 

We can see that if any element is present an odd number of times , then there will be no pair for it.

Since, to get XOR 0, we require to pair number ‘a’ with the same number.

Thus, we can just check if any element is present an odd number of times.

  • If yes, we return false.
  • Else, we return true.
     

Algorithm : 

  • Maintain a HashMap.
  • Run a for loop from ‘i’ =1 to ‘i’ = ‘N’.
  • Inside this for loop :
    • Put the element at this index in the map and increment its previous frequency.
  • Traverse the HashMap
    • If any value is having odd frequency, return false.
  • Return true.