Skip to content

Commit 9d8846a

Browse files
authored
Create TheDuplicateXorArrayProblem-II.cpp
1 parent 02118af commit 9d8846a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//Given: An array A with all elements occuring twice except for x and y that occur once.
2+
//To Do: Find the x and y in O(1) space and O(N) time
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
const int N = 1e6;
6+
int arr[N];
7+
8+
bool hasBitSet(int n, int x) {
9+
int tem = n & (1<<x);
10+
return tem!=0;
11+
}
12+
13+
int main() {
14+
int n;
15+
cin >> n;
16+
17+
int all = 0;
18+
int ans[2] = {0,0};
19+
20+
for(int i=0; i<n; i++){
21+
cin >> arr[i];
22+
all ^= arr[i];
23+
}
24+
25+
//assert(all != 0);
26+
int k = 0;
27+
while( hasBitSet(all, k) == 0 ) k++;
28+
29+
//parition array into two sets: kth bit on v/s off
30+
for (int i=0; i<n; i++) {
31+
ans[hasBitSet(arr[i], k)] ^= arr[i];
32+
}
33+
34+
cout << ans[0] << " " << ans[1] << endl;
35+
return 0;
36+
}

0 commit comments

Comments
 (0)