Wednesday, August 31, 2011

Find the Number Occurring Odd Number of Times others Even number of times

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.

Example: 
I/P = [1, 2, 3, 2, 3, 1, 3]
O/P = 3

Algorithm: 
Do bitwise XOR of all the elements. Finally we get the number which has odd occurrences.


Program:

#include 
int getOddOccurrence(int ar[], int ar_size)
{
     int i;
     int res = 0;
     for(i=0; i < ar_size; i++)
        res = res ^ ar[i];
     return res;
}
/* Diver function to test above function */
int main()
{
     int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
     printf("%d", getOddOccurrence(ar, 13));
     getchar();
}

1 comment:

  1. Doing xor with the same number yields 0 as output and 0 xor X will yield X. so all even digits get cancelled producing 0 which will be Xor'd with the left out odd digit producing the same number.

    ReplyDelete