Finding the number, occurring odd number of times in an array
Given an array arr[]
of n
integers, find a number which occurred odd times in the array. If such an element exists, print that respective element, else print There is no odd occurring element
.
Note: The array should contain at most one odd times occurring number.
Method 1 ( Hashing ):
Approach: Create an empty hash table. Copy the input array elements into the HashMap such that it contains key as element and value as frequency( count of occurrences ) of that element. Now traverse the HashMap and check for the odd occurrence using divisibility test. If found, print the element.
For example:
In the above example, the input elements {2, 3, 10, 5, 2, 10, 10, 5, 3} are mapped into a hash table with keys {2, 3, 5, 10} with respective values {2, 2, 2, 3}.
When HashMap is traversed from the beginning, the odd occurred element (here 10) can be found with a divisibility test(by 2).
Complexity Analysis : Time Complexity : O(n) Space Complexity: O(n)
{tab title="C++" class="green"}
{tab title="Java" class="orange"}
{tab title="Python" class="red"}
{/tabs}
Method 2 ( Using XOR)
This is the most effective and efficient algorithm to find an odd occurring element from a given array. It uses two basic properties of XOR: Self-inverse and Identity properties which mean-Any element XORed with itself gives zero(A ⊕ A = 0)
and any element XOR’d with zero left unchanged (A ⊕ 0 = A)
respectively.
Approach: Initialize a variable( say result ) to 0. Traverse the array from the beginning and Compute XOR of each and every element with the result variable. So outputting the result variable gives the desired output.
For example
Complexity Analysis :
Time Complexity : O(n)
Space Complexity: O(1)
{tab title="C++" class="green"}
{tab title="Java" class="orange"}
{tab title="Python" class="red"}
{/tabs}