C Programming-Find the Number Occurring Odd Number of Times

C Programming-Find the Number Occurring Odd Number of Times – Bit Algorithm – Given an array of positive integers. All numbers occur 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.

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

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts number of occurrences of the element picked by outer loop. 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 is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.

Below are implementations of this best approach.


[pastacode lang=”c” manual=”%2F%2FC%20program%20to%20find%20the%20element%20occurring%20odd%20number%20of%20times%0A%20%0A%23include%20%3Cstdio.h%3E%0Aint%20getOddOccurrence(int%20ar%5B%5D%2C%20int%20ar_size)%0A%7B%0A%20%20%20%20%20int%20i%3B%0A%20%20%20%20%20int%20res%20%3D%200%3B%20%0A%20%20%20%20%20for%20(i%3D0%3B%20i%20%3C%20ar_size%3B%20i%2B%2B)%20%20%20%20%20%0A%20%20%20%20%20%20%20%20res%20%3D%20res%20%5E%20ar%5Bi%5D%3B%0A%20%20%20%20%20%20%0A%20%20%20%20%20return%20res%3B%0A%7D%0A%20%0A%2F*%20Diver%20function%20to%20test%20above%20function%20*%2F%0Aint%20main()%0A%7B%0A%20%20%20%20%20int%20ar%5B%5D%20%3D%20%7B2%2C%203%2C%205%2C%204%2C%205%2C%202%2C%204%2C%203%2C%205%2C%202%2C%204%2C%204%2C%202%7D%3B%0A%20%20%20%20%20int%20n%20%3D%20sizeof(ar)%2Fsizeof(ar%5B0%5D)%3B%0A%20%20%20%20%20printf(%22%25d%22%2C%20getOddOccurrence(ar%2C%20n))%3B%0A%20%20%20%20%20return%200%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/]



Time Complexity:


Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like