When you know a thing, to hold that you know it, and when you do not know a thing, to allow that you do not know it - this is knowledge. -Confucius-

The gift of fantasy has meant more to me than my talent for absorbing positive knowledge. -Albert Einstein-

Science investigates religion interprets. Science gives man knowledge which is power religion gives man wisdom which is control. -Martin Luther King, Jr.-

Those who have knowledge, don't predict. Those who predict, don't have knowledge. -Lao Tzu-

Our treasure lies in the beehive of our knowledge. We are perpetually on the way thither, being by nature winged insects and honey gatherers of the mind. -Friedrich Nietzsche-

Showing posts with label code hacks. Show all posts
Showing posts with label code hacks. Show all posts

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;
}