File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Famous-Coding-Interview-Problems Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments