VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-two-numbers-with-odd-occurences-in-an-unsorted-array/

⇱ Numbers with odd occurrences - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numbers with odd occurrences

Last Updated : 3 Oct, 2025

Given an unsorted array in which all numbers occur an even number of times except two numbers that occur an odd number of times. Return those two numbers.

Examples: 

Input: [12, 23, 34, 12, 12, 23, 12, 45]
Output: [34, 45]

Input: [4, 4, 100, 5000, 4, 4, 4, 4, 100, 100]
Output: [100, 5000]

Input: [10, 20]
Output: [10, 20]

[Naive Approach] - O(n^2) time and O(1) space

The idea is to run two nested loops. The outer loop picks an element and the inner loop counts the number of occurrences of the picked element. If the count of occurrences is odd, then append the element to result, while ensuring that one element is only pushed once into result.


Output
45 34

[Better Approach - 1] Using Sorting - O(n logn) time and O(1) space

The idea is to use sorting and then find the frequency of each element in linear time.


Output
45 34

[Better Approach - 2] Using Hash Map - O(n) time and O(n) space

The idea is to use a hash map to store the count of all values. Then iterate through the map and return the values with odd count.

Step by step approach:

  1. Traverse all elements and insert them in to a hash table. Element is used as key and the frequency is used as the value in the hash table. 
  2. Iterate through the map and append the values with odd count.

Output
45 34

[Expected Approach] Using Bit Manipulation - O(n) time and O(1) space

To find the two numbers occurring odd times, we first compute the XOR of all array elements, resulting in x ^ y, because elements occurring even times cancel out. This XOR value tells us where x and y differ. We then find the rightmost set bit in this XOR value to use as a distinguishing filter. Using this bit, we divide the array into two groups: one where this bit is set and one where it is not. Since x and y differ at this bit, they end up in different groups. Finally, by Xoring all elements within each group, even-count elements cancel out, leaving us with x in one group and y in the other. These two unique numbers are then returned in decreasing order.


Output
45 34
Comment
Article Tags: