Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the only unpaired element in the array

Tags:

algorithm

Accenture interview question:

You have been given an array of size 2n+1 that have n pair of integers (can be +ve, -ve or 0) and one unpaired element.

How would you find the unpaired element?

Pair means duplicate. So (3,3) is a pair and (3,-3) is not a pair.

like image 713
karank Avatar asked Apr 15 '10 09:04

karank


People also ask

How do you find unpaired elements in an array?

Naive Approach In the naive approach, we try to search the array linearly for the pair of each element. Once we find an element that doesn't have a pair, we declare it as the answer to the problem. loop. , then the current element was unpaired.

How do I find a single element in an array?

The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence.

How do you find unique elements in an array using XOR?

The way to find the unique element is by using the XOR bitwise operator which returns 1 only if one of the element is 1 and false otherwise. In the loop, each of the integers in the array are XORed with uniqueId starting at 0. Then, 0 is XOR'ed with 34.


1 Answers

Take XOR of all the elements.

The pairs will cancel out as

a XOR a = 0 

and the result will be the only unpaired element as

0 XOR a = a 

If its okay to destroy the array you can XOR adjacent elements. Once done the last element of the array has the unpaired element:

N = Num of elements in array. for( i=1 to N )    arr[i] ^= arr[i-1];     print arr[N-1] 

If its not okay to destroy the array, you can make use of a variable to hold the result:

N = Num of elements in array. Unpaired = arr[0]; for( i=1 to N )    Unpaired = Unpaired ^ arr[i];     print Unpaired 

C function to do the same:

int findUnpaired(int *arr,int len) {  int i;                  // loop counter.  int unpaired;           // to hold the unpaired element.   unpaired = arr[0];      // initialize it with the 1st array ele.   for(i=1;i<len;i++) {    // loop for all remaining elements.     unpaired ^= arr[i];  // XOR each element with the running XOR.  }  return unpaired;        // return result. } 
like image 175
codaddict Avatar answered Sep 19 '22 10:09

codaddict