Monday, May 23, 2016

Finding the unpaired element in an array

Given an integer array there are odd number of elements (each are between 1 and 100). Except for one all others have a duplicate in the array.

ex : [1, 3, 4, 5, 7, 6, 7, 5, 3, 1, 4]

in here only unpaired element is 6. Target is to find the unpaired element of this array.

We can use the Exclusive Or operation to solve this.

The property we are going to use is for an integer 'a' the vale a^a is zero and 0^a is 'a'. When we get the XOR of the given array elements altogether the answer will be the isolated element.

int notPaired(int[] n) {
    int ans = 0 ;
    for (int e:n)
        ans ^= e;
    return ans;
}



0 comments:

Post a Comment