[Geeks for Geeks] Two numbers with odd occurrences

Two numbers with odd occurrences

Given an unsorted array, arr[] of size N and that contains even number of occurrences for all numbers except two numbers. Find the two numbers in decreasing order which has odd occurrences.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
public:
vector<int> twoOddNum(int Arr[], int N) {
int mask = 0;
for(int i = 0; i < N; i++) {
mask ^= Arr[i];
}

mask = mask & ~(mask - 1);

int xor1 = 0, xor2 = 0;
for(int i = 0; i < N; i++) {
if(mask & Arr[i]) xor1 ^= Arr[i];
else xor2 ^= Arr[i];
}
return {max(xor1, xor2), min(xor1, xor2)};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/two-numbers-with-odd-occurrences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.