[Geeks for Geeks] Non Repeating Numbers

Non Repeating Numbers

Given an array A containing 2 x N+2 positive numbers, out of which 2 x N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution
{
public:
vector<int> singleNumber(vector<int> nums)
{
int n = nums.size();
int mask = 0;
for(auto& n : nums) {
mask ^= n;
}
mask = mask & (~(mask - 1));
int a = 0, b = 0;
vector<int> res;
for(auto& n : nums) {
if(mask & n) a ^= n;
else b ^= n;
}
return {min(a,b), max(a,b)};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/finding-the-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.