![]() |
VOOZH | about |
Given an array arr[] of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times.
Examples :
Input : arr[]= [1, 2, 3, 2, 3, 1, 3]
Output : 3Input : arr[] = [5, 7, 2, 7, 5, 2, 5]
Output : 5
Table of Content
A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and the inner loop counts the number of occurrences of the element picked by the outer loop.
5
Time Complexity: O(n^2)
Auxiliary Space: O(1)
A Better Solution is to use Hashing. Use array elements as a key and their counts as values. Create an empty hash table. One by one traverse the given array elements and store counts.
5
Time Complexity: O(n)
Auxiliary Space: O(n)
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring elements.
Here ^ is the XOR operators;
x ^ 0 = x
x ^ y=y ^ x (Commutative property holds)
(x ^ y) ^ z = x ^ ( y ^ z) (Distributive property holds)
x ^ x=0
5
Time Complexity: O(n)
Auxiliary Space: O(1)