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

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.

[ad type=”banner”]

Program:

[pastacode lang=”java” manual=”%2F%2FJava%20program%20to%20find%20the%20element%20occurring%20odd%20number%20of%20times%0A%20%0Aclass%20OddOccurance%20%0A%7B%0A%20%20%20%20int%20getOddOccurrence(int%20ar%5B%5D%2C%20int%20ar_size)%20%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20int%20i%3B%0A%20%20%20%20%20%20%20%20int%20res%20%3D%200%3B%0A%20%20%20%20%20%20%20%20for%20(i%20%3D%200%3B%20i%20%3C%20ar_size%3B%20i%2B%2B)%20%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20res%20%3D%20res%20%5E%20ar%5Bi%5D%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20return%20res%3B%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20OddOccurance%20occur%20%3D%20new%20OddOccurance()%3B%0A%20%20%20%20%20%20%20%20int%20ar%5B%5D%20%3D%20new%20int%5B%5D%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%20%20%20%20int%20n%20%3D%20ar.length%3B%0A%20%20%20%20%20%20%20%20System.out.println(occur.getOddOccurrence(ar%2C%20n))%3B%0A%20%20%20%20%7D%0A%7D%0A%2F%2F%20This%20code%20has%20been%20contributed%20by%20Mayank%20Jaiswal%0A” message=”Java Programming” highlight=”” provider=”manual”/]

Output:

5


Time Complexity:
O(n)

[ad type=”banner”]