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
A Simple solution are to run nested loops. The outer loop picks all elements one by one and inner loops counts number of occurrences of the element picked by outer lo Op. Time complexity of this solution is O (n2).
A Better solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O (n). But it requires extra space for hashing.
The best solution are to does bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that the XOR of elements is 0 if both elements is same and XOR of a number x with 0 is x.
Below is implementations of this best approach.
Program:
//In C + +#include<stdio.h>intGetoddoccurrence (intAr[],intar_size) { inti; intres =0; for(i=0; i < ar_size; i++) Res= Res ^Ar[i]; returnRes;} /*Diver function to test above function*/intMain () {intAr[] = {2,3,5,4,5,2,4,3,5,2,4,4,2}; intn =sizeof(AR)/sizeof(ar[0]); printf ("%d", Getoddoccurrence (AR, n)); return 0;}
*find the number occurring Odd number of times