VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-occurring-odd-number-of-times/

⇱ Number occurring odd number of times - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number occurring odd number of times

Last Updated : 30 Aug, 2025

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 : 3

Input : arr[] = [5, 7, 2, 7, 5, 2, 5]
Output : 5

[Naive Approach] Using Nested Loop

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.


Output
5

Time Complexity: O(n^2)
Auxiliary Space: O(1)

[Another Approach]Using Hashing

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.


Output
5

Time Complexity: O(n)
Auxiliary Space: O(n)

[Expected Approach] Using Bit Manipulation

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

Output
5

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment